我有一个应用程序,允许用户在有限的时间内在结构画布上绘图。时间结束后,我想结束绘图模式并将绘图保存为图像。
我的问题是,如果时间在用户仍在绘制时拖动(拖动鼠标),则绘图将消失(再次单击画布后)。
以下小提琴示例显示了我所做的应用程序,产生问题的步骤是:
代码示例:
var canvas = new fabric.Canvas("c",{backgroundColor : "#fff"});
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = "green";
canvas.freeDrawingBrush.width = 4;
setTimeout(stop_drawing, 3000);
function stop_drawing() {
canvas.isDrawingMode = false;
}
小提琴示例:
答案 0 :(得分:5)
您可以模仿library中发生的事情:
_onMouseUpInDrawingMode: function(e) {
this._isCurrentlyDrawing = false;
if (this.clipTo) {
this.contextTop.restore();
}
this.freeDrawingBrush.onMouseUp();
this._handleEvent(e, 'up');
},
在你的情况下,你只需要发起onMouseUp
事件,所以你的函数stop_drawing将是:
function stop_drawing() {
canvas.isDrawingMode = false;
canvas.freeDrawingBrush.onMouseUp();
}
在我们的案例中onMouseUp将是:
/**
* Invoked on mouse up
*/
onMouseUp: function() {
this._finalizeAndAddPath();
},
让我们看看它是如何运作的_finalizeAndAddPath:
/**
* On mouseup after drawing the path on contextTop canvas
* we use the points captured to create an new fabric path object
* and add it to the fabric canvas.
*/
_finalizeAndAddPath: function() {
var ctx = this.canvas.contextTop;
ctx.closePath();
var pathData = this.convertPointsToSVGPath(this._points).join('');
if (pathData === 'M 0 0 Q 0 0 0 0 L 0 0') {
// do not create 0 width/height paths, as they are
// rendered inconsistently across browsers
// Firefox 4, for example, renders a dot,
// whereas Chrome 10 renders nothing
this.canvas.renderAll();
return;
}
var path = this.createPath(pathData);
this.canvas.add(path);
path.setCoords();
this.canvas.clearContext(this.canvas.contextTop);
this._resetShadow();
this.canvas.renderAll();
// fire event 'path' created
this.canvas.fire('path:created', { path: path });
}
此时绘制的路径已添加到画布中。
我更新了您的代码段here 如果你想看看下面的代码......
一切顺利
var canvas = new fabric.Canvas("c", {
backgroundColor: "#fff"
});
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = "green";
canvas.freeDrawingBrush.width = 4;
setTimeout(stop_drawing, 3000);
function stop_drawing() {
canvas.isDrawingMode = false;
canvas.freeDrawingBrush.onMouseUp();
}

<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="500" height="500" style="border:1px solid #ccc"></canvas>
&#13;