Glen Elkins
Glen Elkins

Reputation: 917

FabricJS 2- Setting fill on SVG paths when only single path

So adding an SVG to the canvas as follows:

// load the svg
fabric.loadSVGFromURL(self.currentDraggedIcon, function(objects, d) {

  var iconGroup = fabric.util.groupSVGElements(objects, d);
  iconGroup.set({
    left: e.layerX,
    top: e.layerY,
    width: d.width,
    height: d.height,
    lockUniScaling: true,
    //  scaleY:self.currentObjectDesigner.scaleFactor,
    // scaleX:self.currentObjectDesigner.scaleFactor,
    dtype: 'UserIcon'
  });

  self.currentObjectDesigner.fabric.add(iconGroup);
  self.currentObjectDesigner.fabric.bringToFront(iconGroup);
  self.currentObjectDesigner.fabric.renderAll();
});

Later on there is a button to say change the paths colour to red inside the group, the code to do this is:

for (var i = 0; i < self.currentObjectDesigner.selectedObject._objects.length; i++) {

  if (self.currentObjectDesigner.selectedObject.item(i).fill == findColor || self.currentObjectDesigner.selectedObject.item(i).fill == findColorAlt) {
    self.currentObjectDesigner.selectedObject.item(i).fill = color;

  }
}

self.currentObjectDesigner.selectedObject.addWithUpdate();

This works perfectly fine if the SVG has multiple paths, but when only a single path exists the _objects property doesn't exist so we are unable to perform the loop and item(i) part to set the fill on the path.

Question is: How do we now set a fill when _objects doesn't exist and the item() method doesn't exist because it's just a single path? - I.e it's not a group.

Upvotes: 1

Views: 1733

Answers (1)

Durga
Durga

Reputation: 15604

If more than one path present groupSVGElements returns group objects else returns a single object.

DEMO

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

function loadSvg(url, left, top) {
  fabric.loadSVGFromURL(url, function(objects, d) {
    var iconGroup = fabric.util.groupSVGElements(objects, d);
    //for more than one path
    iconGroup.set({
      left: left,
      top: top
    })
    if (iconGroup.type == 'group') {
      //do your logic for group object
      iconGroup.item(0).fill = 'yellow';
      iconGroup.addWithUpdate();
    } else {
      iconGroup.fill = 'red';
    }
    iconGroup.set({
      scaleX: 150 / iconGroup.width,
      scaleY: 150 / iconGroup.height,
    })
    canvas.add(iconGroup);
  }, function() {}, {
    crossOrigin: 'anonymous'
  });

}
loadSvg('https://upload.wikimedia.org/wikipedia/commons/2/22/Wikimapia_logotype.svg', 10, 20);
loadSvg('https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg', 200, 50);
canvas{
 border:2px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='c' width=400 height=400></canvas>

Upvotes: 2

Related Questions