在本教程中,我們將學(xué)習(xí)如何使用 FabricJS 將 Line 對(duì)象在畫布上水平居中。 Line 元素是 FabricJS 中提供的基本元素之一。它用于創(chuàng)建直線。由于線元素在幾何上是一維的并且不包含內(nèi)部,因此它們永遠(yuǎn)不會(huì)被填充。我們可以通過(guò)創(chuàng)建 fabric.Line 實(shí)例來(lái)創(chuàng)建線條對(duì)象,指定線條的 x 和 y 坐標(biāo)并將其添加到畫布中。為了使線條對(duì)象在畫布上水平居中,我們使用 centerH 方法。
語(yǔ)法
centerH()
登錄后復(fù)制
Line 對(duì)象的默認(rèn)外觀
示例
讓我們看一個(gè)代碼示例,看看不使用 centerH 方法時(shí)我們的 line 對(duì)象的外觀。在這種情況下,線條對(duì)象將不會(huì)在畫布上水平居中。
<!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>Default appearance of the Line object</h2>
<p>You can see that the line object has not been centered horizontally on the canvas</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);
</script>
</body>
</html>
登錄后復(fù)制
使用centerH方法
示例
在這個(gè)例子中,我們將看到如何通過(guò)使用centerH方法,我們能夠?qū)⒕€條對(duì)象精確地放置在畫布的水平中心。在這種情況下,對(duì)象水平居中。
<!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 the centerH method</h2>
<p>
You can see that the line object has been centered horizontally on the canvas
</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 the centerH() method to center line object horizontally
line.centerH();
</script>
</body>
</html>
登錄后復(fù)制
以上就是FabricJS – 如何將 Line 對(duì)象在畫布上水平居中?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






