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?
you can fix the 'jumping' polygon by setting the originX and originY points on initialization.
See here: http://jsfiddle.net/ujefxh7w/48/
I don't know why the selection box is shifted.
EDIT: found that reloading of the canvas object fixes the select box
serializing, and loading the serialized objects does the trick:
http://jsfiddle.net/ujefxh7w/50/
There are two solutions to this problem, which are very very simple:
Solution #1
Just remove the polygon from the canvas and recreate it (using new fabric.Polygon(...)) on every added point!
Pros & Cons: Yes, you will get a slightly worse performance, because the canvas will be rerendered twice, but you will save yourself the trouble of recalculating the coordinates every time.
You can check this solution out in the snippet below or in this forked fiddle.
Solution #2
Recalculate the polygon dimensions every time, like it is done in the constructor of Polygon class. Excerpt from the code:
Pros & Cons: Better performance (probably noticeable on heavily loaded canvases), but you will have more code as you have to add it to both handlers.
You can check this out in the snippet below or in this forked fiddle.
Problem definition
When the polygon is added as static object (in sense that the points won't be modified) it's
left, right, minX, minY, width, height
and center point can be calculated based on provided points.But when one wants a polygon to be created dynamically the problem arises. After calling
setCoords()
it calculates the locations of the move boxes but it's based on the incorrect information about width and height.Remember, when creating 1 point Polygon, it has width and height equal to 0, and the top left is equal to that one point.
Solution
First, correct the size
_calcDimensions()
calculateswidth
,height
,minX
andminY
of the polygon.minX
andminY
are the minima in all points.This informs us how far left and top above the old center some points were placed. We should use this information to move the old left to the correct spot. The new top-left point is the old center point translated by the
minX
andminY
information.Fix points
After the center has moved by some vector
v
(a result of changingleft
,right
andwidth
,height
properties). We need to updated all points by a reverse ofv
.Check following Fiddle for the full example: http://jsfiddle.net/orian/dyxjkmes/5/
Copy&paste