在本教程中,我們將展示如何使用 FabricJS 獲取線的坐標。 Line 元素是 FabricJS 中提供的基本元素之一。它用于創建直線。由于線元素在幾何上是一維的并且不包含內部,因此它們永遠不會被填充。我們可以通過創建 fabric.Line 的實例來創建線條對象,指定線條的 x 和 y 坐標并將其添加到畫布中。為了獲取 Line 對象的坐標,我們使用 getCoords 方法。
語法
getCoords(): Array
登錄后復制
使用 getCoords 方法
示例
讓我們看一個代碼示例,以查看 getCoords 方法執行時記錄的輸出用過的。 getCoords 方法以數組格式返回 Line 的左上角、右上角、右下角和左下角坐標。
<!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 getCoords method</h2>
<p>You can open console from dev tools and see the logged output</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a Line object
var line = new fabric.Line([50, 100, 310, 100], {
stroke: "blue",
strokeWidth: 10,
});
// Add it to the canvas
canvas.add(line);
// Using getCoords method
console.log("The coordinates are: ", line.getCoords());
</script>
</body>
</html>
登錄后復制
使用 getCoords 方法繪制斜線
示例
在此示例中,我們使用了 getCoords 方法獲取具有不同起始和結束坐標的 Line 實例的坐標。我們可以看到記錄的輸出是:(100, 40)、(220, 40)、(220,120)、(100,120),分別是該行的左上角、右上角、右下角和左下角坐標.
<!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 getCoords method for a slant line</h2>
<p>You can open console from dev tools and see the logged output</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a Line object
var line = new fabric.Line([200, 100, 100, 40], {
stroke: "blue",
strokeWidth: 20
});
// Add it to the canvas
canvas.add(line);
// Using getCoords method
console.log("The coordinates are: ", line.getCoords());
</script>
</body>
</html>
登錄后復制
以上就是如何使用 FabricJS 獲取 Line 對象的坐標?的詳細內容,更多請關注www.92cms.cn其它相關文章!






