Dhananjaya Dhananjaya - 4 months ago 78
JSON Question

fabric js loadFromJSON issue

i'm working on this graphic visualizer. following is a example code of what i'm doing.
first i create new canvas and there is a simple jQuery click event to add image objects to canvas.and after working on this canvas i need to load data from database, I've managed to save data on database by "Serialization" which default support by fabric-js. and retrieve data as a json object to load in to canvas. what i want is to completely remove current working canvas and load a new with database retrieved data. so here what i've done so far...

(function() {

var canvasOffsetHeight = '400';
var canvasOffsetWidth = '600';

var canvas = new fabric.Canvas('canvas');

window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
canvas.setHeight(canvasOffsetHeight);
canvas.setWidth(canvasOffsetWidth);
canvas.renderAll();
}
// resize on init
resizeCanvas();

jQuery('.category ul').on('click', 'li', function (e) {
var imgElement = jQuery(this).children("img")[0];

var imgInstance = new fabric.Image(imgElement, {
left: 100,
top: 100,
angle: 0,
opacity: 1
});
canvas.add(imgInstance);
canvas.renderAll();

return false;

});

jQuery('#obj').click(function(){

canvas_data = '{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"selectable":true,"hasControls":true,"hasBorders":true,"hasRotatingPoint":false,"transparentCorners":true,"perPixelTargetFind":false,"rx":0,"ry":0}],"background":"rgba(0, 0, 0, 0)"}';

var canvas = new fabric.Canvas('canvas');

canvas.loadFromJSON(canvas_data,canvas.renderAll.bind(canvas));

});


})();

here lets assume "canvas_data" is the data from database.
the problem is when i load data from an object it appears on canvas correctly but soon as i click on them they just vanishing.

i think because main function run onLoad so when i click it triggers the main function and load the previous canvas. what i want is to wipe out old canvas and load new one with database data. please help.
they say "loadFromJSON" automatically does this for us but it seems not working for me.

Answer

No need to create another canvas object. So your code in the #obj.click becomes:

jQuery('#obj').click(function(){

    canvas_data = '{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"selectable":true,"hasControls":true,"hasBorders":true,"hasRotatingPoint":false,"transparentCorners":true,"perPixelTargetFind":false,"rx":0,"ry":0}],"background":"rgba(0, 0, 0, 0)"}';



    canvas.loadFromJSON(canvas_data,canvas.renderAll.bind(canvas));

});