I'm facing an issue with saving and loading dynamic patterns applied to objects. I've tried to find a solution online without success. I understand the reason behind the problem but I'm unsure how to fix it.
This is basically what I'm doing:
- Applying dynamic pattern to object.
- Saving canvas to MongoDB using 'JSON.stringify(canvas.toJSON([...])'.
- Loading canvas using 'loadFromJSON'.
- Encountering error 'Uncaught ReferenceError: patternSourceCanvas is not defined'.
All the information I've come across on this problem dates back at least 2 years ago, some even from 2013, with no concrete working example with code.
UPDATE
Below is the function I use to apply patterns on paths:
function applyPatternOnPath(p, image, width, patternRepeat, patternPadding) {
if (patternRepeat) {
var r = 'repeat'
} else {
var r = 'no-repeat'
}
fabric.Image.fromURL(image, function(img) {
var padding = 0 + patternPadding;
img.scaleToWidth(width);
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
patternSourceCanvas.renderAll();
var pattern = new fabric.Pattern({
source: function() {
patternSourceCanvas.setDimensions({
width: img.getScaledWidth() + padding,
height: img.getScaledHeight() + padding
});
patternSourceCanvas.renderAll();
return patternSourceCanvas.getElement();
},
repeat: r
});
p.set('fill', pattern);
canvas.renderAll();
}, { crossOrigin: 'Anonymous' });
}