Fabricjs prevent freedrawing outside of canvas boundaries

Viewed 830

How can i prevent user from drawing outside of the canvas in freedrawing mode.

User can't start drawing from the outside but it can start drawing from inside and drag the mouse outside the canvas and then return inside and release the mouse button.

Part of the line will be drawn outside of the canvas. How can I tell fabric to stop drawing when mouse moves outside of canvas?

I tried this :

_onMouseOut(e) {
  if(this.canvas.isDrawingMode) {
    this.canvas.trigger('mouse:up');
    this.canvas.isDrawingMode = false;
  }
}

not working.and this :

_onMouseOut(e) {
  if(this.canvas.isDrawingMode) {
    this.canvas.freeDrawingBrush.onMouseUp();
    this.canvas.isDrawingMode = false;
  }
}

things gets funcky...

also returning false from mouse:move has no effect on this.

UPDATE : this almost worked but its still funcky ...

_onMouseOver(event) {     

  if (Util.isDefined(this.canvas.__isDrawingMode)) {
    this.canvas._isCurrentlyDrawing = true;
    delete this.canvas.__isDrawingMode;
  }
}

_onMouseOut(e) {
  if(this.canvas.isDrawingMode) {
    this.canvas.__isDrawingMode = this.canvas.isDrawingMode;
    this.canvas._isCurrentlyDrawing = false;
    // this.canvas.isDrawingMode = false;
  }
}

UPDATE2 : Tried clipTo but its not working properly on a canvas that is scaled with setDimensions({},cssOnly:true);

    this.canvas.clipTo = (ctx) => {
      ctx.rect(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
    };
1 Answers

For future users here is the link to a solution.

const canvas = new fabric.Canvas('canvas', {
  isDrawingMode: true
});
canvas.freeDrawingBrush.limitedToCanvasSize = true;
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.4/fabric.min.js"></script>

<canvas id="canvas" style="border: 1px solid black; width: 100px: heigth:200px"></canvas>

Related