简体   繁体   English

fabric.js如何使用fromObject api

[英]fabric.js how to use fromObject api

I want to implement importing data from one template into another without affecting data from the other. 我想实现从一个模板到另一个模板的导入数据,而又不影响另一个模板的数据。 Using deserialization API loadFromJson will empty the canvas data first, so I want to use toObect method to export the data, and then use toFromObject to import, but the object cannot display correctly after the import, may I ask if there is any solution?Or is there another implementation?thank you 使用反序列化API loadFromJson将首先清空画布数据,因此我想使用toObect方法导出数据,然后使用toFromObject导入,但是导入后对象无法正确显示,请问是否有解决方案?还有其他实现吗?谢谢

demo: https://jsfiddle.net/laibin/gpvef0k5/2/ 演示: https : //jsfiddle.net/laibin/gpvef0k5/2/

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.3.2/fabric.min.js"></script>
<canvas id="canvas" style="border: 1px solid black" height=480 width=460></canvas>
<button id="btn">导出</button>
<canvas id="canvas_template" style="border: 1px solid black; margin-top: 20px" height=480 width=660></canvas>

Javascript: Javascript:

var canvas = new fabric.Canvas('canvas');
var canvas_template = new fabric.Canvas('canvas_template');

var circle = new fabric.Circle({
    radius: 50, left: 275, top: 75, fill: '#aac'
})

var triangle = new fabric.Triangle({
    width: 100, height: 100, left: 50, top: 300, fill: '#cca'
});

var rect1 = new fabric.Rect({
    width: 200, height: 100, left: 0, top: 50, angle: 30,
    fill: 'rgba(255,0,0,0.5)'
});
var group = new fabric.Group([circle, triangle, rect1])
canvas.add(group).setActiveObject(group);
canvas.renderAll();

document.querySelector('#btn').addEventListener('click',function() {
    var data = group.toObject();
    let newGroup = new fabric.Group([]);

    fabric.Group.fromObject(data, function(obj) {
        console.log('newGroup', obj)
        canvas_template.setActiveObject(obj).renderAll();
    })
})

You never added the resulting object to canvas, that's why you didn't see it, only the selection made by setActiveObject() . 您从未将结果对象添加到画布,这就是为什么您看不到它的原因,仅看到setActiveObject()所做的选择。 You should add the object in the fromObject() callback: 您应该在fromObject()回调中添加对象:

fabric.Group.fromObject(data, function(obj) {
  canvas_template.add(obj) // <- like this
  console.log('newGroup', obj)
  canvas_template.setActiveObject(obj).renderAll();
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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