如何使用FabricJS以编程方式实现delete-all操作
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松地定制它。
为了以编程方式实现delete-all,我们需要使用clear方法。这个方法清除了一个实例的所有上下文。
语法
clear(): fabric.Canvas
例子1:在Polygon上用程序实现delete-all
让我们看一个代码例子来了解我们如何在Polygon上以编程方式实现delete-all。我们创建了一个名为Remove()的函数,当我们点击移除按钮时,该函数将被调用。在这里,我们使用了clear()方法来删除画布上的所有Polygon实例。
<!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>Implementing delete-all programmatically on Polygon</h2>
<p>
You can click on the Remove button which removes all instances of Polygon from the canvas
</p>
<button id="btn" onclick="Remove()" style="padding: 3px">Remove</button>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating Remove function
function Remove() {
canvas.clear().renderAll();
}
// Initiating a polygon object
var polygon1 = new fabric.Polygon(
[
{ x: 30, y: 50 },
{ x: 70, y: 50 },
{ x: 0, y: 0 },
{ x: 70, y: 0 },
],
{
left: 110,
top: 40,
fill: "#1e90ff",
strokeWidth: 4,
stroke: "black",
scaleX: 1.5,
scaleY: 1.5,
objectCaching: false,
}
);
// Initiating another polygon object
var polygon2 = new fabric.Polygon(
[
{ x: 60, y: 90 },
{ x: 100, y: 20 },
{ x: 55, y: 40 },
{ x: 75, y: 50 },
],
{
left: 200,
top: 60,
fill: "#080808",
strokeWidth: 4,
stroke: "red",
scaleX: 1.5,
scaleY: 1.5,
objectCaching: false,
}
);
// Adding them to the canvas
canvas.add(polygon1, polygon2);
</script>
</body>
</html>
例2:在矩形上以编程方式实现delete-all
让我们看一个代码例子来了解我们如何在矩形上以编程方式实现delete-all。我们已经启动了两个矩形对象,并将它们添加到画布上。只要我们点击删除按钮,所有的对象就会从画布上被删除。
<!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>Implementing delete-all programmatically on Rectangle</h2>
<p>
You can click on the Remove button which removes all instances of rectangle from the canvas
</p>
<button id="btn" onclick="Remove()" style="padding: 3px">Remove</button>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating Remove function
function Remove() {
canvas.clear().renderAll();
}
// Initiating a rectangle object
var rectangle1 = new fabric.Rect({
width: 50,
height: 30,
left: 110,
top: 40,
fill: "#1e90ff",
strokeWidth: 4,
stroke: "black",
objectCaching: false,
});
// Initiating another rectangle object
var rectangle2 = new fabric.Rect({
width: 50,
height: 30,
left: 200,
top: 60,
fill: "#080808",
strokeWidth: 4,
stroke: "red",
objectCaching: false,
});
// Adding them to the canvas
canvas.add(rectangle1, rectangle2);
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS以编程方式实现delete-all操作。