FabricJS – 如何将 Line 对象置于画布当前视口的中心?

在本教程中,我们将学习如何使用 FabricJS 将 Line 对象在画布的当前视口中水平和垂直居中。 Line 元素是 FabricJS 中提供的基本元素之一。它用于创建直线。由于线元素在几何上是一维的并且不包含内部,因此它们永远不会被填充。我们可以通过创建 Fabric.Line 的实例、指定线的 x 和 y 坐标并将其添加到画布来创建线对象。为了使 Line 对象在画布的当前视口上居中,我们使用 viewportCenter 方法。
语法
viewportCenter(): fabric.Object
Line 对象的默认外观
示例
让我们看一个代码示例,看看不使用 viewportCenter 方法时 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 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: 20,
});
// Add it to the canvas
canvas.add(line);
</script>
</body>
</html>
使用viewportCenter方法
示例
让我们看一个代码示例,看看使用 viewportCenter 方法时线条对象的样子。在这种情况下,我们的线条对象将相对于画布的当前视口居中。
<!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 viewportCenter method</h2>
<p>
You can see that the line object is centered 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: 20,
});
// Add it to the canvas
canvas.add(line);
// Using the viewportCenter method
line.viewportCenter();
</script>
</body>
</html>
javascript