在fabricjs中克隆svg时出错

时间:2016-09-20 09:12:26

标签: javascript svg fabricjs

我正在尝试从相同的数据中克隆几个svgs,但是当我将颜色应用于其中一个时,它也适用于其他数据。我不确定我是否正确克隆了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);							

  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");								
      }						
      else{

        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>	

1 个答案:

答案 0 :(得分:0)

我认为你只是错误地克隆了对象。

&#13;
&#13;
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);
      }
    }
  }
}
&#13;
<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>
&#13;
&#13;
&#13;