Search code examples
fabricjs

freeDrawingBrush.onMouseMove fix x or y to draw only straight line


I am trying to draw a straight line making x fix using freeDrawingBrush.

For example:

          canvas.isDrawingMode = 1;
          canvas.freeDrawingBrush.color = "purple";
          canvas.freeDrawingBrush.width = 10; 

          canvas._onMouseMoveInDrawingMode = function (e) {
           
                var pointer = canvas.getPointer(e);
                pointer.x = 100;
                
                this.freeDrawingBrush.onMouseMove(pointer);
            
        }

this doing the work but it is drawing continuously on mousemove. I want user to be able to draw multiple lines at a fix (for e.g.) x=100 at distances on y-axis.

Update:

I added following code :

          canvas._onMouseUpInDrawingMode = function (e) {


            this._isCurrentlyDrawing =  false;
            //canvas.selection = true;
            canvas.isDrawingMode = 0;

            this.freeDrawingBrush.onMouseUp();
            this._handleEvent(e, 'up');

        }

This stops drawing continuously but new problem raised. When I enable drawing mode again and try to draw new line it also add previous line to new line


Solution

  • After a lot of research I found the way:

    var brush = new fabric.PencilBrush(canvas);
    canvas.isDrawingMode = 1;
    brush.width = 10;
         
    canvas._onMouseMoveInDrawingMode = function (e) {
           
        var pointer = canvas.getPointer(e);
        pointer.x = 100;
                
        brush.onMouseDown({x:pointer.x, y:pointer.y});
            
    }