如何使用FabricJS将仅选择的折线分组为单个对象
我们可以通过创建 fabric.Polyline 的实例来创建一个折线对象。折线对象可以由一组连接的直线段组成。由于它是FabricJS的基本元素之一,我们还可以通过应用属性(如角度、不透明度等)来轻松自定义它。要将多个折线对象分组,我们可以使用 toGroup() 方法。
语法
toGroup(): Fabric.Group
示例1:创建一个 fabric.Polyline() 的实例并将其添加到我们的画布上
在查看如何将多个对象分组之前,让我们看一个代码示例,其中我们将一个折线对象添加到我们的画布上。唯一必需的参数是 points 数组,而第二个参数是可选的 选项 对象。
<!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:一键分组选择的折线
在这个示例中,我们将有一个按钮,点击该按钮时,选择的折线将被分组为一个单独的对象。因此,移动该对象将移动所有已分组的折线,并且在调整大小或倾斜时行为像一个单一的对象。
我们将创建一个函数,用于获取画布中所有选择的对象,并将它们分组为一个单独的对象。
<!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 only selected Polyline objects using one click</h2>
Select the polylines by dragging on required area and click on the`Group` Button to group all the selected Polyline objects in the canvas
<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: 100 },
{ x: 150, y: 60 },
{ x: 250, y: 10 },
], {
stroke: "green",
fill: "white",
strokeWidth: 5,
});
// Initiate another Polyline object
var polyLine3 = new fabric.Polyline([
{ x: 400, y: 200 },
{ x: 250, y: 160 },
{ x: 150, y: 200 },
], {
stroke: "green",
fill: "white",
strokeWidth: 5,
});
// Add them to the canvas instance
canvas.add(polyLine1);
canvas.add(polyLine2);
canvas.add(polyLine3);
// Function to group the selected polyline objects into single object
function group() {
canvas.getActiveObject().toGroup();
}
</script>
</body>
</html>