I'm currently trying to use the fabric.js library to fill a PNG or a SVG with a pattern. 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):
// 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);
before adding the SVG, I get this result:
(so the pattern is loaded as it should).
I think I'm getting pretty close, must be missing the KEY
line in the code. 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.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);
});
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.