Snouto
Snouto

Reputation: 1031

Reloading JSON fails to render correctly in canvas with Fabric.js

I have a bit of an issue with Fabric.js. I'm loading a JSON string in to the canvas and then at some time in the future I want to load more JSON in again (possibly the same JSON). The first load seems to work fine but the second load has an issue: the foreground path object doesn't appear, even though its bounding box is clickable. I'm not sure if this is a problem relating to the backgroundImage, or the way I'm clearing the canvas before I load the JSON again, or the actual way I'm loading JSON (or all three).

I've put a simple fiddle here.

var j = { ... }; //json object (see fiddle)
var c = new fabric.Canvas( document.getElementById("c") );

c.loadFromJSON(j, function(objects, options) {
c.renderAll();

setTimeout(function(){
    c.backgroundImage=0;
    c.clear();
    c.renderAll();

    setTimeout(function(){

        c.loadFromJSON(j, function(objects, options) {
            c.renderAll();
            c.setActiveObject(c.item(0));
        });

    },3000);
},3000);

});

I create the initial canvas view from the JSON object, then clear it out after 3 seconds, then load it in again after another 3 seconds (this is just to simulate clicking a button or whatever in a real app).

Would appreciate any help on this and apologies if this has been dealt with before.

Cheers

[EDIT] I've noticed that if I copy the JSON object in to a second variable so that i'm initialising two objects with the same content, and load that in the second loop, it will load again properly. Could the original JSON variable be getting modified or cached and that's causing the issue? (fiddle for this here

Upvotes: 1

Views: 1644

Answers (1)

Theo Itzaris
Theo Itzaris

Reputation: 4671

i checked the objects that you product and i see that when you load the svg for the second time, all the 'paths' object is missing.

you can see it too, by adding a console.log before the first load and another one just before the 2nd load. like this:

console.log(JSON.stringify(j));

anyway, to the point, you just need to stringify your object before you try to load it, in that way you keep all the object as one ,

i added a line that converts you svg object to json string and pass it on a temp variable

tmp = JSON.stringify( j );

take a look ,i update your code,on the fiddle: https://jsfiddle.net/5j7ejLmk/2/

if you find my answer correct please mark it as so. good luck

Upvotes: 1

Related Questions