在本教程中,我們將學習如何使用 FabricJS 將 Line 對象在畫布的當前視口上垂直居中。 Line 元素是 FabricJS 中提供的基本元素之一。它用于創建直線。由于線元素在幾何上是一維的并且不包含內部,因此它們永遠不會被填充。我們可以通過創建 fabric.Line 實例來創建線條對象,指定線條的 x 和 y 坐標并將其添加到畫布中。為了使 Line 對象在畫布的當前視口上垂直居中,我們使用 viewportCenterV 方法。
語法
viewportCenterV(): fabric.Object
登錄后復制
Line 對象的默認外觀
示例
讓我們看一個代碼示例,看看不使用 viewportCenterV 方法時我們的 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>Default appearance of the Line object</h2>
<p>
You can see that the line object is not centered vertically with respect to the current viewport of 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: 6,
});
// Add it to the canvas
canvas.add(line);
</script>
</body>
</html>
登錄后復制
使用viewportCenterV方法
示例
讓我們看一個代碼示例,看看當
使用viewportCenterV方法。在這種情況下,我們的線條對象將垂直居中
相對于畫布的當前視口。
<!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 viewportCenterV method</h2>
<p>
You can see that the line object is centered vertically with respect to the current viewport of 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: 6,
});
// Add it to the canvas
canvas.add(line);
// Using the viewportCenterV method
line.viewportCenterV();
</script>
</body>
</html>
登錄后復制
以上就是FabricJS – 如何使 Line 對象在畫布的當前視口上垂直居中?的詳細內容,更多請關注www.92cms.cn其它相關文章!






