I expanded the Fabric library to perform a similar function.
First create the fabricExtensions.js file and include it immediately after you have loaded the material library in the header section of your page.
<script type="text/javascript" src="fabric.min.js"></script> <script type="text/javascript" src="fabricExtensions.js"></script>
Inside the newly created fabricExtensions.js file fabricExtensions.js add the following code:
fabric.Canvas.prototype.getItemByAttr = function(attr, name) { var object = null, objects = this.getObjects(); for (var i = 0, len = this.size(); i < len; i++) { if (objects[i][attr] && objects[i][attr] === name) { object = objects[i]; break; } } return object; };
What this block of code does is it allows you to select an object by any attribute assigned to it.
Now, to remove an object, this should work:
canvas.fabric.getItemByAttr('id', myID).remove();
This method will allow you to configure ANY attribute set for the object. Alternatively, you can change it to something like this to set up only the exact attribute you were looking for:
fabric.Canvas.prototype.getItemByMyID = function(myID) { var object = null, objects = this.getObjects(); for (var i = 0, len = this.size(); i < len; i++) { if (objects[i].id&& objects[i].id=== myID) { object = objects[i]; break; } } return object; };
And delete the object:
canvas.fabric.getItemByMyID(myID).remove();
source share