This is the function I use to add an object:
function _addImageObject(imageURL) {
fabric.util.loadImage(imageURL, function (imageLoaded) {
var image = new fabric.Image(imageLoaded);
image.set({
borderColor: 'black',
cornerColor: 'black',
cornerStrokeColor: 'white',
cornerSize: 11,
transparentCorners: false,
});
canvas.add(image);
canvas.centerObject(image);
canvas.setActiveObject(image);
canvas.renderAll();
});
}
Function used to get the objects:
function _canvasJSON() {
try {
let canvasCopy = _copyCanvas(canvas);
let canvasJSON = {
canvasImage: JSON.stringify(canvasCopy),
svg: canvas.toSVG()
};
return canvasJSON;
} catch (e) {
canvas.renderAll();
}
}
function _copyCanvas() {
let canvasString = JSON.stringify(canvas);
return JSON.parse(canvasString);
}
I'd like to add an object inside this image, just like this:
image.set('key', { values: 123});
And be able to get it from the return of _canvasJSON().
If you need to add/get any custom key&value pair to any fabricJS object, you can do that as you do with any other key&value pair:
image.set('width', 100);
image.get('width');
image.set('customKey', 'Custom value added here');
image.get('customKey');
image.set({
borderColor: 'black',
values: 123
transparentCorners: false,
});
image.get('values');
If you need to export a fabricJS canvas, use this:
const customKeys = ['customKey', 'values'];
canvas.toJSON(customKeys);
toJSON() accepts an array as a parameter. That array MUST include any custom key that you've attached to any object. It also needs any key that it's not part of the 'default' keys from an object(e.g: 'evented', hoverCursor', 'scaleX', etc.)
use canvas.loadFromJSON(json) to load the exported json.
More details about toJSON in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With