FabricJS – 如何獲取影像物件相對於原點的座標?


在本教程中,我們將學習如何使用 FabricJS 獲取影像物件相對於原點的座標。我們可以透過建立fabric.Image的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆地自定義它。為了獲取影像物件相對於原點的座標,我們使用getPointByOrigin方法。

語法

getPointByOrigin(originX: String, originY: String): fabric.Point 

引數

  • originX − 此引數接受一個字串,用於指定水平原點。可能的值為“left”,“center”或“right”。

  • originY − 此引數接受一個字串,用於指定垂直原點。可能的值為“top”,“center”或“bottom”。

使用getPointByOrigin方法

示例

讓我們看一個程式碼示例,以檢視使用getPointByOrigin方法時的日誌輸出。getPointByOrigin方法返回使用者指定原點的物件的座標。在本例中,我們也使用了getCenterPoint方法,以便您可以看到給定影像物件的實際中心點。而在使用getPointByOrigin方法時,我們取左下角為原點,因此日誌輸出為 x= 110 和 y= 132。

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using getPointByOrigin method</h2> <p> You can open console from dev tools and see that the logged output contains the coordinates </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // Add it to the canvas canvas.add(image); // Using getCenterPoint method console.log( "The real center point of the object is: ", image.getCenterPoint() ); // Using getPointByOrigin method console.log( "The coordinates returned while using getPointByOrigin method are: ", image.getPointByOrigin("left", "bottom") ); </script> </body> </html>

使用不同值的getPointByOrigin方法

示例

在此示例中,我們使用了getPointByOrigin方法來獲取影像物件的座標,其中水平和垂直中心點分別為“right”和“top”。這意味著右上角將被視為中心。

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using getPointByOrigin method with different values</h2> <p> You can open console from dev tools and see that the logged output contains the coordinates </p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.tw/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // Add it to the canvas canvas.add(image); // Using getPointByOrigin method console.log( "The coordinates returned while using getPointByOrigin method are: ", image.getPointByOrigin("right", "top") ); </script> </body> </html>

更新於: 2022年10月27日

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告