如何使用 FabricJS 将多个 Polyline 对象组合成单个对象?
我们可以通过创建fabric.Polyline的实例来创建一个 Polyline 对象。Polyline 对象可以由一组连接的直线段来表征。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松自定义它。为了组合多个 Polyline 对象,我们可以使用toGroup()方法。
语法
toGroup(): Fabric.Group
示例 1:创建 fabric.Polyline() 的实例并将其添加到画布
在了解如何将多个对象组合成一个对象之前,让我们先看一个代码示例,说明如何将 polyline 对象添加到画布中。唯一需要的参数是points数组,第二个参数是可选的options对象。
<!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> Creating an instance of fabric.Polyline() and adding it to our canvas </h2>
<p>You can see that the polyline object has been added</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating a points array
var points = [
{ x: 30, y: 50 },
{ x: 0, y: 0 },
{ x: 60, y: 0 },
];
// Initiating a polyline object
var polyline = new fabric.Polyline(points, {
left: 100,
top: 40,
fill: "white",
strokeWidth: 4,
stroke: "green",
});
// Adding it to the canvas
canvas.add(polyline);
</script>
</body>
</html>
示例 2:一键组合所有 Polyline
在这个例子中,我们将有一个按钮,单击该按钮将所有 Polyline 组合成一个对象。因此,移动该对象将移动所有 Polyline,并且在调整大小或倾斜时,它也将表现为单个对象。我们将创建一个函数,该函数获取画布中的所有对象并将它们组合成一个对象。
<!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>Grouping all the Polyline objects using one click</h2>
<p> Click on the `Group` Button to group all the Polyline objects in the canvas </p>
<canvas id="canvas"></canvas>
<button type="button" onclick="group()">Group</button>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a Polyline object
var polyLine1 = new fabric.Polyline([
{ x: 500, y: 200 },
{ x: 550, y: 60 },
{ x: 350, y: 100 },
], {
stroke: "green",
fill: "white",
strokeWidth: 5,
});
// Initiate another Polyline object
var polyLine2 = new fabric.Polyline([
{ x: 300, y: 200 },
{ x: 150, y: 60 },
{ x: 250, y: 100 },
], {
stroke: "green",
fill: "white",
strokeWidth: 5,
});
// Add them to the canvas instance
canvas.add(polyLine1);
canvas.add(polyLine2);
// Function to group all the polyline objects into single object
function group() {
// Get all the objects as selection
var sel = new fabric.ActiveSelection(canvas.getObjects(), {
canvas: canvas,
});
// Make the objects active
canvas.setActiveObject(sel);
// Group the objects
canvas.getActiveObject().toGroup();
}
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP