如何使用 FabricJS 以编程方式实现全选删除操作?
我们可以通过创建fabric.Polygon的实例来创建多边形对象。多边形对象可以由任何由一组连接的直线段组成的闭合形状来表示。由于它是 FabricJS 的基本元素之一,因此我们还可以通过应用角度、不透明度等属性轻松地对其进行自定义。
为了以编程方式实现全选删除,我们需要使用clear方法。此方法清除实例的所有上下文。
语法
clear(): fabric.Canvas
示例 1:在多边形上以编程方式实现全选删除
让我们来看一个代码示例,了解如何在多边形上以编程方式实现全选删除。我们创建了一个名为Remove()的函数,当我们点击Remove按钮时将调用该函数。在这里,我们使用了clear()方法从画布中删除所有多边形实例。
<!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:在矩形上以编程方式实现全选删除
让我们来看一个代码示例,了解如何在矩形上以编程方式实现全选删除。我们初始化了两个矩形对象并将它们添加到画布中。一旦我们点击Remove按钮,所有对象都将从画布中删除。
<!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 以编程方式实现全选删除操作。
广告