Draw a line while pressed mouse is moved over the canvas

Code below is  drawing line by mowing mouse on canvas while  left mouse button is pressed . My needs variate from it because it clears all other existing shapes on canvas and it draws curve line as mouse is making path while moving over the canvas.

What I need is to have straight line from point when mouse was pressed  to  the point where mouse is in that moment while mouse is moving and to finish the line  after mouse is relisted.  And then to press mouse again at point where previous line was finished , drew another line same way as first was created and so on until polyline is complete.
I was trying also other codes but now i think i am on right way to achieve what is needed and  that it will not interfere  with my existing  app.

I am using fabric.js.








var Paramter = function(){

    this.flag = false,  //
    this.type = 'line', //
    this.point = [],    //
    this.lineWidth =1,      //
    this.lineStyle = [0,0],   //
    this.lineColor = 'rbga(0,0,0,1)', //
    this.fillColor = 'rbga(0,0,0,1)',  //
    this.ctn = undefined                  //

}

Paramter.prototype.setValue = function(key,value){
    for(var i in this){
        if(this.hasOwnProperty(i)){
            if(i===key){
                this[i] = value;
                return;
            }
        };
    }
}

Paramter.prototype.getValue = function(key){
    return this[key]
}
Paramter.prototype.addKey = function(key,val){
    this[key] = val;
}
Paramter.prototype.removeKey = function(key){
    this[key] = undefined;
}
var para = new Paramter();



var canvasWrite = new fabric.Canvas('canvas',{
    allowTouchScrolling:false,
    isDrawingMode : false
});

canvas.on('mouse:down',function(e){
    if(para.type!='line') return;
    var _point = [];
    _point.push({
        x:e.e.x,
        y:e.e.y
    });
    para.setValue('point',_point);
    para.setValue('flag',true);
});

canvas.on('mouse:move',function(e){
    if(!para.flag) return;
   canvas.clear()
    var _point = para.point;
    _point.push({
        x:e.e.x,
        y:e.e.y
    });
    para.setValue('point',_point);
    var line = new fabric.Polyline(_point,{
        left:_point[0]['x'],
        top:_point[0]['y'],
        strokeWidth : para.getValue('lineWidth'),
        stroke : para.getValue('lineColor'),
        strokeLineCap:'round',
        strokeLineJoin:'round',
        fill:null
    });
    line.setShadow('0px 0px 3px rgba(0,0,0,1)')
    canvas.add(line)
});

canvas.on('mouse:up',function(e){
    para.setValue('point',[]);
    para.setValue('flag',false);
});

Open in new window

Ivan GolubarAsked:
Who is Participating?
 
Leonidas DosasCommented:
An example without fabric.js
<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
  <style>
   #drawCanvas{
    position:absolute;
    top:0;
    left:0;
}
  </style>
</head>
<body>
<!-- Start your code here -->

<canvas id="canvas"></canvas>
<canvas id="drawCanvas"></canvas>
  <script>
   var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    drawCanvas = document.getElementById("drawCanvas"),
    drawCtx = drawCanvas.getContext("2d"),
    painting = false,
    lastX = 0,
    lastY = 0,
    curX = 0,
    curY = 0,
    startX = 0,
    startY = 0,
    lineThickness = 1;

canvas.width = canvas.height = 600;

drawCanvas.width = drawCanvas.height = 600;

drawCanvas.onmousedown = function(e) {
    painting = true;
    drawCtx.fillStyle = "#000";
    lastX = e.pageX - this.offsetLeft;
    lastY = e.pageY - this.offsetTop;
    startX = lastX;
    startY = lastY;
};

drawCanvas.onmouseup = function(e){
    painting = false;
    var x2 = e.pageX - this.offsetLeft,
        y2 = e.pageY - this.offsetTop;
    
    ctx.strokeStyle = "#000";
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    
    drawCtx.clearRect(0, 0, 600, 600);
}
    
drawCanvas.onmouseclick = function(e) {
    drawCtx.fillStyle = "#000";
    lastX = e.pageX - this.offsetLeft;
    lastY = e.pageY - this.offsetTop;
    startX = lastX;
    startY = lastY;

    if(painting){
        
    }

    else{
        painting = true;
        lastX = e.pageX - this.offsetLeft;
        lastY = e.pageY - this.offsetTop;
        startX = lastX;
        startY = lastY;
    }
};

drawCanvas.onmousemove = function(e) {
    if (painting) {
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;

        // find all points between        
        var x1 = mouseX,
            x2 = lastX,
            y1 = mouseY,
            y2 = lastY;


        var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
        if (steep){
            var x = x1;
            x1 = y1;
            y1 = x;

            var y = y2;
            y2 = x2;
            x2 = y;
        }
        if (x1 > x2) {
            var x = x1;
            x1 = x2;
            x2 = x;

            var y = y1;
            y1 = y2;
            y2 = y;
        }

        var dx = x2 - x1,
            dy = Math.abs(y2 - y1),
            error = 0,
            de = dy / dx,
            yStep = -1,
            y = y1;
        
        if (y1 < y2) {
            yStep = 1;
        }
       
      
        for (var x = x1; x < x2; x++) {
            if (steep) {
                drawCtx.fillRect(y, x, lineThickness , lineThickness );
            } else {
                drawCtx.fillRect(x, y, lineThickness , lineThickness );
            }
            
            error += de;
            if (error >= 0.5) {
                y += yStep;
                error -= 1.0;
            }
        }



        lastX = mouseX;
        lastY = mouseY;

    }
}

  </script>
<!-- End your code here -->
</body>
</html>

Open in new window

0
 
Ivan GolubarAuthor Commented:
If i understand well  we have two canvas one over another.

In my app i already have two canvas in different positions on main page.

For testing of your code i will make new php page . Which i will open from link on main page.

For now I don't want  to  interfere with my existing canvas.

Thank you
0
 
Ivan GolubarAuthor Commented:
It is working.
let me study how to proceed.

Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.