Aditya Deshmane Aditya Deshmane - 2 months ago 47
JSON Question

FabricJS how to re-add stringified json object (Deserialize)

I have one canvas object in JSON format.

{"type":"rect",
"originX":"left",
"originY":"top",
"left":100,
"top":100,
"width":200,
"height":200,
"fill":"blue",
"stroke":null,
"strokeWidth":1,
"strokeDashArray":null,
"strokeLineCap":"butt",
"strokeLineJoin":"miter",
"strokeMiterLimit":10,
"scaleX":1,"scaleY":1,
"angle":0,
"flipX":false,
"flipY":false,
"opacity”:1,
”shadow":null,
"visible":true,
"clipTo":null,
"backgroundColor":"",
"fillRule":"nonzero",
"globalCompositeOperation":"source-over",
"transformMatrix":null,
"skewX":0,
"skewY":0,
"rx":0,
"ry":0}


How to deserialize this object to re-add it using
canvas.add()
?

I don't want to use
canvas.loadFromJSON()
as it clears current canvas content.

Answer

Yeah unfortunately canvas.loadFromJSON() clears the canvas first. You could try something like this:

var canvas;

        var json = '{"objects": [{"type":"rect", "left":100, "top":100, "width":200, "height":200, "fill":"blue"}]}';
        canvas = new fabric.Canvas('c');

        // Create an object to show that this doesn't get overwritten when we load the JSON
        var circle = new fabric.Circle({
            radius: 50, fill: 'green', left: 50, top: 50
        });
        canvas.add(circle);
        canvas.renderAll();

        // Parse JSON and add objects to canvas
        var jsonObj = JSON.parse(json);
        fabric.util.enlivenObjects(jsonObj.objects, function (enlivenedObjects) {
            enlivenedObjects.forEach(function (obj, index) {
                canvas.add(obj);
            });
            canvas.renderAll();
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>

<canvas id="c" width="600" height="400">    </canvas>

Or for just one object:

var json = '{"type":"rect", "left":100, "top":100, "width":200, "height":200, "fill":"blue"}';
        canvas = new fabric.Canvas('c');

        // Create an object to show that this doesn't get overwritten when we load the JSON
        var circle = new fabric.Circle({
            radius: 50, fill: 'green', left: 50, top: 50
        });
        canvas.add(circle);
        canvas.renderAll();

        // Parse JSON and single object to canvas
        var jsonObj = JSON.parse(json);
        fabric.util.enlivenObjects([jsonObj], function (enlivenedObjects) {
            canvas.add(enlivenedObjects[0]);
            canvas.renderAll();
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
    <canvas id="c" width="600" height="400"></canvas>