Advena
Advena

Reputation: 2233

FabricJS - Create rectangle using 4 points (tl,tr, bl, br)?

Creating a rectangle in FabricJs is straightforward using top, left, width and height values.

After moving, scaling and rotating the rectangle around, one can get the rectangle's definitive coordinate using the aCoords of the object, returning bl, br, tl, tr x and y coordinates of the rectangles four edges.

How can one recreate the same rectangle using only these four coordinates, which also include rotation and scaling?

I was only able to recreate the rectangle after it has been moved and scaled, but not with rotations.

FabricJS create rectangle using only coordinates issue

This above image is a screenshot of the following jsFiddle: https://jsfiddle.net/7neukojd/32/

As you can see, the left side is the original rectangle (blue), which has been scaled, moved and rotated. The right side rectangle (red) is me, trying to copy it using only the bl, br, tl and tr coordinates.

Upvotes: 0

Views: 1279

Answers (1)

Advena
Advena

Reputation: 2233

Thanks to asturur, this issue has been solved with the following code

  let rectObj = canvas1.getObjects()[0];
  const tl = rectObj.aCoords.tl;
  const tr = rectObj.aCoords.tr;
  const bl = rectObj.aCoords.bl;
  
  let rectCopy = new fabric.Rect({
    left: rectObj.aCoords.tl.x,
    top:  rectObj.aCoords.tl.y,
    width: (new fabric.Point(tl.x, tl.y).distanceFrom(tr)),
    height: (new fabric.Point(tl.x, tl.y).distanceFrom(bl)),
    angle: fabric.util.radiansToDegrees(Math.atan2(tr.y - tl.y, tr.x - tl.x)),
    fill: "red",
  })

Source: https://github.com/fabricjs/fabric.js/discussions/6834#discussioncomment-314599

Upvotes: 0

Related Questions