fabric js loadFromJSON问题

时间:2016-08-07 07:38:22

标签: javascript json object canvas fabricjs

我正在研究这个图形可视化工具。以下是我正在做的示例代码。 首先我创建新的画布,并有一个简单的jQuery点击事件,以将图像对象添加到canvas.and在这个画布上工作后,我需要从数据库加载数据,我已设法通过“序列化”保存数据库,默认支持by fabric-js。并将数据作为json对象检索以加载到画布中。我想要的是完全删除当前工作画布并加载一个新的数据库检索数据。所以我到目前为止所做的...

(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));

});

})();

这里假设“canvas_data”是来自数据库的数据。 问题是当我从一个对象加载数据时它正确地出现在画布上,但是当我点击它们时它们就会消失。

我认为因为main函数运行onLoad所以当我点击它时会触发main函数并加载上一个画布。我想要的是擦除旧画布并加载新的数据库数据。请帮忙。 他们说“loadFromJSON”会自动为我们做这件事,但似乎对我不起作用。

1 个答案:

答案 0 :(得分:2)

无需创建另一个画布对象。所以#obj.click中的代码变为:

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));

});