Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js: How to draw a polygon by mouse

Tags:

fabricjs

I want draw a fabric.Polygon with mouse interaction in Fabric.js. I made a small jsfiddle to show my actual state: http://jsfiddle.net/Kienz/ujefxh7w/

After pressing the ESC key, the "interactive draw mode" is canceled and the polygon is finalized. But now the position of the polygon is wrong (controls are right).

Has anyone an idea?

like image 730
Kienz Avatar asked Oct 20 '22 00:10

Kienz


1 Answers

For those looking for an updated answer that uses fabricjs 3.

FabricJS had a lot of changes, one of them being to the _calcDimmensions method. It no longer stores the values minX and minY on the object. It instead returns an object with the following:

  {
    left: minX,
    top: minY,
    width: width,
    height: height
  }

So with that in mind, the solution updates to the following:

currentShape.set({
points: points
});
var calcDim = currentShape._calcDimensions();
currentShape.width = calcDim.width;
currentShape.height = calcDim.height;
currentShape.set({
    left: calcDim.left,
    top: calcdim.top,
    pathOffset: {
        x: calcDim.left + currentShape.width / 2,
        y: calcDim.top + currentShape.height / 2
    }
});
currentShape.setCoords();
canvas.renderAll();
like image 77
Visceras Avatar answered Oct 31 '22 01:10

Visceras