Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js - change color/fill/stroke of imported svg

Is there a way to change the color of an svg in fabric placed on the canvas using loadSVGFromURL? The svg is just an arrow, if I can't set the fill or stroke, can I do this with a filter?

$("input:radio[id='arrow']").click(function() {
fabric.loadSVGFromURL('../scripts/svg/arrow.svg', function(objects) {
          var group = new fabric.PathGroup(objects, {
          left: 165,
          top: 100,
          width: 295,
          height: 40,
          fill: colourSet
        });
        canvas.add(group);
        canvas.renderAll();
          }); 
           });
like image 928
IlludiumPu36 Avatar asked Mar 28 '13 06:03

IlludiumPu36


1 Answers

var colorSet = '#00FFFF';

$("input:radio[id='arrow']").click(function() {
  fabric.loadSVGFromURL('../scripts/svg/arrow.svg', function(objects, options) {
    var shape = fabric.util.groupSVGElements(objects, options);
    shape.set({
      left: 165,
      top: 100,
      width: 295,
      height: 40
    });
    if (shape.isSameColor && shape.isSameColor() || !shape.paths) {
      shape.setFill(colorSet);
    }
    else if (shape.paths) {
      for (var i = 0; i < shape.paths.length; i++) {
        shape.paths[i].setFill(colorSet);
      }
    }
    canvas.add(shape);
    canvas.renderAll();
  }); 
});

The function setFill on fabric.PathGroup objects only works if all paths has the same color: https://github.com/kangax/fabric.js/blob/master/src/path_group.class.js#L99

like image 52
Kienz Avatar answered Nov 07 '22 13:11

Kienz