简体   繁体   中英

Fabricjs .toJSON() doesn't save correctly to LocalStorage ([object Object])

I'm utilizing FabricJS and I want to save the resulting canvas on LocalStorage on 'unloading' event, afterwards when reloading the page I want to load the resulting JSON from localStorage to my canvas.

I can see the resulting Object of fabricjs's .toJSON() function is indeed an object, trying to use JSON.stringify(myObject) , to save to LocalStorage causes problems when trying to re-draw the canvas because it changes the JSON structure.

    $( window ).bind('beforeunload', function() {
        const myObject = canvas.toJSON();
        localStorage.setItem('design', canvas.toJSON());
    });

    $(document).ready(function () {
        if (localStorage.getItem("design") !== null) {
            const json = localStorage.getItem("design");
            canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
        }
    });

I'm looking for a way that I can save the canvas without altering the Object structure for when it's returned. Or a way so that when the JSON is retrieved, I can edit it, so it can be redrawn into the canvas.

So, it seems like the Stringify format or Parse function weren't the real problem, the problem was that I was inavertently overwriting the 'type' attribute of every object I added to the canvas, this was the cause of the "not rendering" problem, because the loadFromJSON fabricjs function utilizes the type attribute to create the objects inside the canvas. Final Code:

$( window ).bind('beforeunload', function() {
    const json = canvas.toJSON();
    localStorage.setItem('design', JSON.stringify(json));
});

$(document).ready(function () {
    if (localStorage.getItem("design") !== null) {
        const json = localStorage.getItem("design");
        canvas.loadFromJSON($.parseJSON(json), canvas.renderAll.bind(canvas))
    }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM