fabric.js-鼠标移动时结束自由绘图模式

Osa*_*adi 1 javascript canvas fabricjs

我有一个应用程序,允许用户在有限的时间内绘制织物画布。时间结束后,我想结束绘图模式并将绘图保存为图像。

我的问题是,如果在用户仍在绘制(拖动鼠标)的时间结束时,该绘制将消失(再次单击画布后)。

下面的小提琴示例显示了我制作的应用程序,产生问题的步骤如下:

  1. 运行小提琴,然后立即开始绘制。
  2. 3秒钟后,将发生超时事件,自由绘图模式将结束。并且绘图将停止。
  3. 再次单击画布,然后拖动鼠标。
  4. 绘图将消失。

代码示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

小提琴的例子:

https://jsfiddle.net/usaadi/808x5d20/1/

ale*_*dro 5

您可以模拟库中发生的情况:

_onMouseUpInDrawingMode: function(e) {
  this._isCurrentlyDrawing = false;
  if (this.clipTo) {
    this.contextTop.restore();
  }
  this.freeDrawingBrush.onMouseUp();
  this._handleEvent(e, 'up');
},
Run Code Online (Sandbox Code Playgroud)

就您而言,您只需要触发onMouseUp事件,因此您的功能stop_drawing将为:

function stop_drawing() {
  canvas.isDrawingMode = false;
  canvas.freeDrawingBrush.onMouseUp();

}
Run Code Online (Sandbox Code Playgroud)

在我们的例子中,onMouseUp将是:

/**
* Invoked on mouse up
*/
onMouseUp: function() {
  this._finalizeAndAddPath();
},
Run Code Online (Sandbox Code Playgroud)

让我们看看_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 });
    }
Run Code Online (Sandbox Code Playgroud)

此时,绘制的路径已经添加到画布中。

如果您想看下面的代码,我已经在这里更新了您的代码段...

祝一切顺利

_onMouseUpInDrawingMode: function(e) {
  this._isCurrentlyDrawing = false;
  if (this.clipTo) {
    this.contextTop.restore();
  }
  this.freeDrawingBrush.onMouseUp();
  this._handleEvent(e, 'up');
},
Run Code Online (Sandbox Code Playgroud)
function stop_drawing() {
  canvas.isDrawingMode = false;
  canvas.freeDrawingBrush.onMouseUp();

}
Run Code Online (Sandbox Code Playgroud)