简体   繁体   English

fabric.js用PNG模式填充SVG或PNG

[英]fabric.js fill a SVG or a PNG with a PNG pattern

I'm currently trying to use the fabric.js library to fill a PNG or a SVG with a pattern. 我目前正在尝试使用fabric.js库用模式填充PNG或SVG。 I tried to get some inspiration from there , but couldn't make it work as it is explained. 我试图从得到一些启示那里 ,但不能做,因为它是解释它的工作。

Here is my pattern: 这是我的模式:

在此处输入图片说明

Here is my PNG template (can't upload SVG, but it's here . And the SVG is white): 这是我的PNG模板(无法上传SVG,但是在这里 。并且SVG是白色的):

在此处输入图片说明

// GET AND INIT CANVAS (400x400)
canvas = new fabric.Canvas('canvas');

// MY PATHS
let patternURL = "../images/background1.jpg";
let SVGURL = "../svg/test.svg";

// CREATE MY SVG ELEMENT
fabric.loadSVGFromURL(SVGURL, function(objects, options) {
    // CREATE MY PATTERN IMAGE
    fabric.Image.fromURL(patternURL, function(patternImage) {
        svg = fabric.util.groupSVGElements(objects, options);
        svg = svg.set({"opacity": 1});
        svg.getObjects().forEach(function(e) {
            // IF I DON'T USE THIS LINE, THE SVG REMAIN WHITE
            e.fill = patternImage
        });

        canvas.add(svg);
    });
});

Here is what I have after the execution of my code: 这是我执行代码后的内容:

在此处输入图片说明

NB: I can move the PNG, and if I add canvas.add(patternImage); 注意:我可以移动PNG,如果我添加canvas.add(patternImage); before adding the SVG, I get this result: 在添加SVG之前,我得到以下结果:

在此处输入图片说明

(so the pattern is loaded as it should). (因此该模式会按预期加载)。

I think I'm getting pretty close, must be missing the KEY line in the code. 我想我已经很接近了,必须在代码中缺少KEY行。 Do you have any helpful information or could redirect me into the right place? 您是否有任何有用的信息,或者可以将我重定向到正确的位置?

EDIT: Here is the (sort of, I just did it on paint) background I wish to obtain : 编辑:这是我希望获得的(某种程度上,我刚在油漆上做过)背景:

在此处输入图片说明

You need to create another canvas for your pattern. 您需要为图案创建另一个画布。 And use that in fabric.Pattern and then use that pattern object to fill. 并在fabric.Pattern中使用该样式,然后使用该样式对象进行填充。

fabric.loadSVGFromURL(SVGURL, function(objects, options) {
  fabric.Image.fromURL(patternURL, function(patternImage) {
    svg = fabric.util.groupSVGElements(objects, options);
    var patternSourceCanvas = new fabric.StaticCanvas();
    patternSourceCanvas.add(patternImage);
    patternSourceCanvas.setDimensions({
      width: patternImage.getScaledWidth(),
      height: patternImage.getScaledHeight()
    });
    patternSourceCanvas.renderAll();
    var pattern = new fabric.Pattern({
        source: patternSourceCanvas.getElement()
      },
      function(patternObj) {
        svg.getObjects().forEach(function(e) {
          e.fill = patternObj
        });
        canvas.add(svg);
      });
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM