How do I remove SVG from a Fabric.js canvas?

筅森魡賤 提交于 2019-12-12 01:36:53

问题


So I've deduced that I can add SVG graphics to the canvas by using:

fabric.loadSVGFromURL('img1.svg', function(objects, options) {
    var obj1 = fabric.util.groupSVGElements(objects, options);
    canvas.add(obj1);
}); 

fabric.loadSVGFromURL('img2.svg', function(objects, options) {
    var obj2 = fabric.util.groupSVGElements(objects, options);
    canvas.add(obj2);
}); 

Suppose I now want to delete one or both of those. How can I do that?


回答1:


In fabricjs I use different method to delete object in canvas. this method delete any object in canvas. fabricjs allow to set name for each object so we can use this property to delete object.like this (i use jquery for this:)

var canvas  = new fabric.Canvas('c');
fabric.loadSVGFromURL('test.svg', function(objects, options) {
    var obj2 = fabric.util.groupSVGElements(objects, options);
    obj2.name ="test_svg"   //<<<<<<< here set name
    canvas.add(obj2);
    console.log(canvas.getObjects())
}); 

function del(){
$.each(canvas._objects, function(index, obj) {
     if(obj == null) return;
     $.each(obj, function(attr, value) {
          //console.log( attr + ' == ' + value );
             if(value == "test_svg"){ //<<<<< here we call name
                   //alert(index);
                     canvas.remove(canvas._objects[index]); // here we delete that object
                     canvas.renderAll();
                 }
             });
});
}

I test this from load svg method and its worked.so maybe this is worked for you ..



来源:https://stackoverflow.com/questions/36256147/how-do-i-remove-svg-from-a-fabric-js-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!