Fabric.js:画布上的笔触颜色和宽度svg文件的问题

时间:2017-03-31 13:24:10

标签: javascript canvas svg fabricjs

我正在使用我的项目fabricJS,我有改变笔触颜色和宽度的问题。我的页面上有一些SVG文件,单击用户后可以将此SVG添加到画布并修改其属性。填充它完美的工作,但中风我不能这样做。这是填充代码,它运作良好:

function setImageColor(element) 
{
    var activeObject = canvas.getActiveObject(),
    color = "#"+element.value;

    console.log(color)    
    console.log(activeObject)
    activeObject.set({fill : color});
    canvas.renderAll();
}

jscolor.addEventListener('change', function()
{
    setImageColor(this);
});

以下是在画布上加载SVG元素的代码:

shapes.forEach(function(e)
{
    e.addEventListener("click", function()
    {
        var src = e.src;
        fabric.loadSVGFromURL( src, function(objects, options) 
        {
            var obj = fabric.util.groupSVGElements(objects, options);
            canvas.add(obj).renderAll();
            obj.scaleToHeight(127) 
                .scaleToWidth(90)
                .center() 
                .setCoords();
            canvas.setActiveObject(obj).renderAll();
        });
    });
});

这里是笔划的代码,它不起作用:

function setStrokeColor(element) 
{
    color = "#"+element.value;
    var obj = canvas.getActiveObject();
    console.log(color)    
    console.log(activeObject)
    activeObject.set({stroke : color, strokeWidth: 5});
    canvas.renderAll();
}

var stroke = document.getElementById("stroke");
console.log(stroke)

stroke.addEventListener('change', function()
{
    setStrokeColor(this);
});

1 个答案:

答案 0 :(得分:1)

这应该这样做(感谢SVG路径导出):

fabricjs svg stroke fill color

这是FabricJS代码:

fabric.loadSVGFromString('<svg id="Warstwa_1" data-name="Warstwa 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{fill:none;stroke:#000;stroke-miterlimit:10;}</style></defs><title>generator ikon</title><path class="cls-1" d="M60,35A25,25,0,1,1,35,10,25,25,0,0,1,60,35Z"/></svg>', function(objects, options) {
  var shape = fabric.util.groupSVGElements(objects, options);
  shape.set({
    left: 50,
    top: 50,
    scaleX: 3,
    scaleY: 3
  });
  if (shape.paths) {
    for (var i = 0; i < shape.paths.length; i++) {
      shape.paths[i].set({
        fill: 'red',
        stroke: 'green',
        strokeWidth: 5
      });
    }
  }
  object = shape;
  canvas.add(shape);
  canvas.renderAll();
});
var switchColors = true;
document.getElementsByTagName("button")[0].addEventListener('click', function() {
  if (object.paths) {
    for (var i = 0; i < object.paths.length; i++) {
      object.paths[i].set({
        fill: (switchColors ? 'green' : 'red'),
        stroke: (switchColors ? 'red' : 'green'),
        strokeWidth: (switchColors ? 10 : 5)
      });
    }
  }
  switchColors = !switchColors;
  canvas.renderAll();
});

这是所有重要的JSFiddle,https://jsfiddle.net/rekrah/wg2qxc8e/

如果您有任何问题,请告诉我。我希望它有所帮助!