FabricJS如何重新添加字符串化的json对象(反序列化)

时间:2016-09-14 10:07:51

标签: javascript json canvas

我有一个JSON格式的画布对象。

{"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}

如何反序列化此对象以使用canvas.add()重新添加它?

我不想使用canvas.loadFromJSON(),因为它会清除当前的画布内容。

1 个答案:

答案 0 :(得分:1)

是的,不幸的是,canvas.loadFromJSON()首先清除了画布。你可以尝试这样的事情:

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>

或仅针对一个对象:

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>