How to set relative position (oCoords) in FabricJs?

假装没事ソ 提交于 2019-12-23 00:50:25

问题


I have a Text in fabricJs. I set top and left. This sets the aCoords properly to those values. However the oCoords dont match. And the Text is not displayed at the right position.

I suspect that I need to set to oCoords somehow. So that the Text is displayed at the right pixel coordinates (top & left) on the canvas.


回答1:


aCoords and oCoords are two different things and should not be in sync.

In your comment you speak about scaled canvas.

Top and Left are 2 absolute values that represent the position of the object on the canvas. This position match with the canvas pixels when the canvas has a identity transform matrix.

If you apply a zoom, this coordinates diverge.

To get the position of pixel 300,100 of the scaled canvas on the unscaled canvas, you need to apply some basic math.

1) get the transform applied to the canvas

canvas.viewportTransform

2) invert it

var iM = fabric.util.invertTransform(canvas.viewportTransform)

3) multiply the wanted point by this matrix

var point = new fabric.Point(myX, myY);
var transformedPoint = fabric.util.transformPoint(point, iM)

4) set the object at that point.



来源:https://stackoverflow.com/questions/45794187/how-to-set-relative-position-ocoords-in-fabricjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!