2016-09-20 47 views
1

我想從相同的數據中克隆幾個svg,但是當我將顏色應用到其中的一個時,它也適用於其他人。我不確定我是否正確地克隆了svg。這裏是我的代碼:在fabricjs中克隆svg時出錯

var canvas = new fabric.Canvas('canvas'); 
 

 
var svgObject = null; 
 

 
fabric.loadSVGFromURL("http://fabricjs.com/assets/131.svg", function(objects, options) { 
 

 
    svgObject = fabric.util.groupSVGElements(objects, options); \t \t \t \t \t \t \t 
 

 
    var object1 = fabric.util.object.clone(svgObject); 
 

 
    colourSVG(object1, "rgb(0,0,0)", "rgba(151,0,0,1)"); 
 

 
    canvas.add(object1); 
 

 
    var object2 = fabric.util.object.clone(svgObject); 
 
    object2.top = 200; 
 
    canvas.add(object2).renderAll(); 
 

 
}); 
 

 
function colourSVG(_obj, _keyColourString, _fillColourString){ 
 

 
    if (!_obj.paths) { 
 
    _obj.setFill(_fillColourString); 
 
    } 
 
    else if (_obj.paths) { 
 
    for (var i = 0; i < _obj.paths.length; i++) { 
 

 
     if(_obj.paths[i].fill === _keyColourString){ 
 
     _obj.paths[i].setFill(_fillColourString); 
 

 
     console.log("colour found"); \t \t \t \t \t \t \t \t 
 
     } \t \t \t \t \t \t 
 
     else{ 
 

 
     console.log(_obj.paths[i].fill); 
 
     } 
 
    } 
 
    } \t 
 
}
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script> 
 

 
<canvas id="canvas" width="800" height="500" ></canvas> \t

+0

難道你不希望克隆之後通過'colourSVG'功能,通過它?也許我對於在初始示例代碼之後何時/如何設置顏色感到困惑? – Anthony

回答

0

我覺得你剛纔克隆的對象不正確。

var canvas = new fabric.Canvas('canvas'); 
 

 
var svgObject = null; 
 

 
fabric.loadSVGFromURL("http://fabricjs.com/assets/131.svg", function(objects, options) { 
 

 
    svgObject = fabric.util.groupSVGElements(objects, options); 
 
    
 
    svgObject.clone(function(o) { 
 
    colourSVG(o, "rgb(0,0,0)", "rgba(151,0,0,1)"); 
 
    canvas.add(o); 
 
    }); 
 
    svgObject.clone(function(o) { 
 
    o.top = 200; 
 
    canvas.add(o); 
 
    }); 
 
    canvas.renderAll(); 
 

 
}); 
 

 
function colourSVG(_obj, _keyColourString, _fillColourString) { 
 

 
    if (!_obj.paths) { 
 
    _obj.setFill(_fillColourString); 
 
    } else if (_obj.paths) { 
 
    for (var i = 0; i < _obj.paths.length; i++) { 
 

 
     if (_obj.paths[i].fill === _keyColourString) { 
 
     _obj.paths[i].setFill(_fillColourString); 
 

 
     console.log("colour found"); 
 
     } else { 
 

 
     console.log(_obj); 
 
     console.log(_obj.paths[i].fill); 
 
     } 
 
    } 
 
    } 
 
}
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script> 
 

 
<canvas id="canvas" width="800" height="500"></canvas>