Fabricjs: fill svg with image pattern

China☆狼群 提交于 2020-01-24 12:24:09

问题


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?


回答1:


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):



来源:https://stackoverflow.com/questions/18588036/fabricjs-fill-svg-with-image-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!