Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

javascript - 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.

question from:https://stackoverflow.com/questions/65919183/fabricjs-create-rectangle-using-4-points-tl-tr-bl-br

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...