Link to home
Start Free TrialLog in
Avatar of Ivan Golubar
Ivan Golubar

asked on

Draw a polyline by clicking on canvas

I am trying to draw polyline by clicking on canvas. I am using library from  fabrics.js. But no result with next code.
Actually i would reader have an example with  "real" polyline because i need a polyline which is one element and not sum of many lines.
Also there  should be also a  way how to define end of one polyline.

 var canvas = new fabric.Canvas('c');
var needFirstPoint = true;

function drawNextLine(ctx, x, y) {
    if (needFirstPoint) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(x, y);
        needFirstPoint = false;
    }
    else {
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}


canvas.on('mouse:down', function(e) {
        var offset = fabric.util.getElementOffset(canvas.lowerCanvasEl);
        var ctx = canvas.getContext('2d');
        var x = e.e.clientX- offset.left;
        var y = e.e.clientY- offset.top;
       drawNextLine(ctx, x, y);
}

Open in new window

Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Something like this?
<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.1/fabric.js"></script>
</head>
<body>
<!-- Start your code here -->

<canvas id="c" width="1500" height="1500" ></canvas>
  <script>
    (function() {
var canvas = new fabric.Canvas('c');
var needFirstPoint = true;

function drawNextLine(ctx, x, y) {
    if (needFirstPoint) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(x, y);
        needFirstPoint = false;
    }
    else {
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}


canvas.on('mouse:down', function(e) {        
        var offset = fabric.util.getElementOffset(canvas.lowerCanvasEl);
        var ctx = canvas.getContext('2d');
        var x = e.e.clientX- offset.left;
        var y = e.e.clientY- offset.top;
        canvas.on('mouse:up',function(ev){       
         drawNextLine(ctx, x, y);
    });
         
});
})();
  </script>
<!-- End your code here -->
</body>
</html>

Open in new window

Avatar of Ivan Golubar
Ivan Golubar

ASKER

Thank you.

When i click for  4.  point i get also connection between  1. and 3. point.
How to get ride of this?
ASKER CERTIFIED SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok.
Thank you.  
Just last thing. If is needed i will open another topic.
What would be the simplest option to finish one polyline? (so then you could start of drawing of another)
I am thinking with a double click event or right click event