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?
The problem is likely that your SVG shape is parsed as a
fabric.PathGroup
rather thanfabric.Path
. Sincefabric.PathGroup
consists of multiplefabric.Path
objects, you need to set their fill value rather than fill value of PathGroup instance itself.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):