在本教程中,我們將學習如何使用 FabricJS 獲取 Image 對象相對于原點的位置。我們可以通過創建fabric.Image的實例來創建一個Image對象。由于它是 FabricJS 的基本元素之一,我們還可以通過應用角度、不透明度等屬性輕松自定義它。為了獲取 Image 對象相對于原點的位置,我們使用 getPointByOrigin 方法。
語法
getPointByOrigin(originX: String, originY: String): fabric.Point
登錄后復制
參數
originX – 此參數接受指定水平原點的String。可能的值為“左”、“中心”或“右”。
originY – 此參數接受表示垂直原點的String。可能的值為“頂部”、“中心”或“底部”。
使用getPointByOrigin方法
示例
讓我們看一個代碼示例,以查看使用 getPointByOrigin 方法時記錄的輸出。 getPointByOrigin 方法返回用戶指定原點的對象坐標。在本例中,我們還使用了 getCenterPoint 方法,以便您可以看到給定 Image 對象的真實中心點。而在使用 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://www.tutorialspoint.com/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’時Image對象的坐標。這意味著右上角的點將被視為中心。
<!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://www.tutorialspoint.com/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>
登錄后復制
以上就是FabricJS – 如何獲取 Image 對象相對于原點的位置?的詳細內容,更多請關注www.92cms.cn其它相關文章!






