user1105595
user1105595

Reputation: 601

Fabricjs: fill svg with image pattern

I’d like to load my SVG file, and fill it with pattern, created from my image file.

Here is my current approach:

canvas = new fabric.Canvas('mainCanvas')
# image = new fabric.Image(img[0])
# console.log image
fabric.loadSVGFromURL '/assets/my.svg',
  (objects) ->
    fabric.util.loadImage "url/to/my/image", (image) ->
      console.log image
      svg = fabric.util.groupSVGElements(objects)
      svg = svg.scale(0.04).set(fill: "black", opacity: 0.5 )
      svg.fill = new fabric.Pattern
        source: image
        repeat: "no-repeat"
      canvas.add(svg)
      canvas.renderAll()

Originally, I tried to use fabric.Image instance (img is jQuery image element, so I’m passing raw htmlelement to constructor), but just to be sure & use code more similar to pattern tutorial I’m using loadImage method.

Unfortunately, this code seems to not work (svg is loaded, but there’s no pattern on it). Is it possible to fill svg with pattern? If so, how can I achieve it?

Upvotes: 2

Views: 5005

Answers (1)

kangax
kangax

Reputation: 39168

The problem is likely that your SVG shape is parsed as a fabric.PathGroup rather than fabric.Path. Since fabric.PathGroup consists of multiple fabric.Path objects, you need to set their fill value rather than fill value of PathGroup instance itself.

if (obj instanceof fabric.PathGroup) {
  obj.getObjects().forEach(function(o) { o.fill = pattern; });
}
else {
  obj.fill = pattern;
}

If you go to kitchensink and use "Patternify" button, you can see that it works with more complex shapes (this is exactly the code we're using there):

enter image description here

Upvotes: 4

Related Questions