Object Deletion in Fabric.js 5: Effortlessly Remove Selected Elements Programmatically

Written by dineshrawat | Published 2023/05/29
Tech Story Tags: programming | fabric.js | object-detection | javascript | html-canvas | programming-tutorial | programming-tips | javascript-development

TLDRFabric.js 5 is an exceptional JavaScript library that empowers developers to create stunning graphical objects and manipulate them effortlessly within HTML5 canvas. Among the various canvas functionalities, the ability to delete selected objects is frequently sought after. via the TL;DR App

Fabric.js 5 is an exceptional JavaScript library that empowers developers to create stunning graphical objects and manipulate them effortlessly within the HTML5 canvas. Among the various canvas functionalities, the ability to delete selected objects is frequently sought after.

In this comprehensive blog post, we will delve into the implementation of programmatically deleting selected objects in Fabric.js 5.

By following this tutorial, you will gain a profound understanding of leveraging the remove method to selectively remove polygons and circles from your canvas.

1: Understanding the Fabric.js 5 Polygon Object and Delete Operation

1.1: The fabric.Polygon Object in Fabric.js 5

The fabric.Polygon object in Fabric.js 5 is a crucial element for constructing closed shapes made up of connected straight-line segments.

Now, let's delve into an example that illustrates the creation of a fabric.Polygon object:

<!DOCTYPE html>
<html>
<head>
<!-- Adding the Fabric JS Library from Cloudflare CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
	// Initialize a canvas instance
	var canvas = new fabric.Canvas("canvas");
	canvas.setWidth(document.body.scrollWidth);
	canvas.setHeight(250);
  // Define the coordinates for the first polygon
  var points1 = [
     { x: 30, y: 50 },
     { x: 70, y: 50 },
     { x: 0, y: 0 },
     { x: 70, y: 0 }
  ];

  // Create the first fabric.Polygon object
  var polygon1 = new fabric.Polygon(points1, {
     left: 100,
     top: 40,
     fill: "#1e90ff",
     strokeWidth: 4,
     stroke: "black",
     scaleX: 1.2,
     scaleY: 1.2
  });

  // Define the coordinates for the second polygon
  var points2 = [
     { x: 60, y: 90 },
     { x: 45, y: 30 },
     { x: 20, y: 48 }
  ];

  // Create the second fabric.Polygon object
  var polygon2 = new fabric.Polygon(points2, {
     left: 30,
     top: 30,
     fill: "#080808",
     strokeWidth: 4,
     stroke: "red",
     scaleX: 2,
     scaleY: 2
  });

  // Add both polygon objects to the canvas
  canvas
        .add(polygon1, 
             polygon2);
</script>
</body>
</html>

We define the coordinates for the two polygons by utilizing the variables points1 and points2. These variables represent the vertices of the polygons, outlining their shape and structure. These polygons are then created using the fabric.Polygon constructor. Each polygon is uniquely customized with specific properties, including its position, fill color, stroke width, stroke color, and scaling. These properties are assigned individually to each polygon, allowing for distinct visual characteristics and appearance.

Finally, we add both the polygon objects, to the canvas using the canvas.add() method. This action ensures that the polygons are displayed and become visible on the canvas.

This code sets up a canvas with two polygons rendered on it, ready for further manipulation or interaction.

1.2: Introducing the Remove Method for Deleting Objects

The remove method in Fabric.js 5 is a pivotal feature that allows the deletion of objects from the canvas. Let's examine its usage through a concise example:

// Removing an object from the canvas using the remove canvas method
canvas.remove(polygon);

By comprehending the fabric.Polygon object and the remove method, you will possess the essential knowledge to implement the delete operation selectively for objects in your Fabric.js 5 applications.

2: Implementing Delete Operation for Selected Polygon Objects Programmatically

2.1: Creating the deletePolygonHandler Function for Removing Selected Polygons

To enable the delete operation for selected polygon objects in Fabric.js 5, we can implement a handy function called deletePolygonHandler. This function will be triggered when a mouse:down event occurs, allowing identification and removal of the selected object from the canvas.

Example code:

// Function to handle deletion of polygons
var deletePolygonHandler = function(obj) {
   var selectedObject = obj.target;
   canvas.remove(selectedObject); // Remove the selected polygon from the canvas
   canvas.renderAll(); // Render the updated canvas
};

// Binding the deletePolygonHandler function to the mouse:down event
canvas.on("mouse:down", deletePolygonHandler);

By binding the deletePolygonHandler function to the mouse:down event, you can effortlessly delete selected polygons within your Fabric.js 5 application. In the subsequent sections, we will further enhance this functionality and explore additional examples.

2.2: Enabling Selective Deletion of Circle Objects Programmatically

In this section, we will demonstrate how to enable the selective deletion of circle objects in Fabric.js 5. By following a similar approach to the one used for polygons, we will introduce the deleteCircleHandler function. This function will be responsible for removing the selected circle object from the canvas upon a mouse:down event.

Let's examine the updated code snippet:

<!DOCTYPE html>
<html>
<head>
  <!-- Adding the Fabric JS Library from Cloudflare CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
	// Initialize a canvas instance
	var canvas = new fabric.Canvas("canvas");
	canvas.setWidth(document.body.scrollWidth);
	canvas.setHeight(250);

  // Define the properties for the first circle
  var circle1 = new fabric.Circle({
     radius: 30,
     left: 100,
     top: 80,
     fill: "#1e90ff",
     strokeWidth: 4,
     stroke: "black",
     scaleX: 1.2,
     scaleY: 1.2
  });

  // Define the properties for the second circle
  var circle2 = new fabric.Circle({
     radius: 15,
     left: 30,
     top: 30,
     fill: "#080808",
     strokeWidth: 4,
     stroke: "red",
     scaleX: 2,
     scaleY: 2
  });

  // Add both circle objects to the canvas
  canvas.add(circle1, circle2);

  // Function to handle deletion of circles
  var deleteCircleHandler = function(obj) {
     var selectedObject = obj.target;
     canvas.remove(selectedObject); // Remove the selected circle from the canvas
     canvas.renderAll(); // Render the updated canvas
  };

  // Bind the deleteCircleHandler function to the mouse:down event
  canvas.on("mouse:down", deleteCircleHandler);
</script>
</body>
</html>

With the addition of the deleteCircleHandler function, you can now effortlessly delete selected circle objects within your Fabric.js 5 application.

Conclusion

In this in-depth blog post, we have explored the process of programmatically deleting selected objects in Fabric.js 5. By mastering the remove method and implementing delete handlers for both polygons and circles, you can empower your canvas-based applications with efficient and intuitive delete functionality.

Armed with the knowledge gained from this tutorial, you are now equipped to elevate your Fabric.js 5 skills and confidently implement powerful object deletion capabilities in your own projects.


Written by dineshrawat | Leading Teams, Building Platforms, and Implementing Innovative Solutions.
Published by HackerNoon on 2023/05/29