问题描述
我正在使用fabricjs开发一个协作白板。当用户创建一个新的结构对象时,我将它序列化并发送给所有其他用户。
I am developping a collaborative whiteboard using fabricjs. When a user creates a new fabric object , I serialize it and send it to all other users.
var rect = new fabric.Rect();
canvas.add(rect);
socket.emit("newObject", JSON.stringify(rect)); // sends the object to other users
当这些用户收到序列化对象时,添加到他们的画布。什么是最好的方法做到这一点?我找不到一个函数反序列化一个对象,只有整个画布(loadFromJSON),所以我实现了一个不太好的解决方案:
When those users receive the serialized object, it should be deserialized and added to their canvas. What is the best way to do this? I was not able to find a function that deserializes a single object, only the whole canvas (loadFromJSON), so I implemented an unelegant solution:
function drawRoomObjects(roomObjects){
var canvasString = "{\"objects\":[";
for(var roomObjectKey in roomObjects){
canvasString += roomObjects[roomObjectKey];
}
canvasString += "], \"background\":\"\"}";
var tmpCanvas = new fabric.Canvas();
tmpCanvas.loadFromJSON(canvasString);
for(var k in tmpCanvas.getObjects()) {
canvas.add(tmpCanvas._objects[k]);
}
canvas.renderAll();
}
有更好的方法吗?
推荐答案
您可以使用 fabric.util.enlivenObjects
反序列化json对象。所有对象反序列化后,您必须添加它们:
You can use fabric.util.enlivenObjects
to deserialize json objects. After all objects are deserialized you have to add them:
objects.forEach(function(o) {
canvas.add(o);
});
这是完整的例子 - 用对象替换obj1,obj2。
示例也可在上使用。
Here is the complete example - replace obj1, obj2 with your objects.Example is also available on jsfiddle.
fabric.util.enlivenObjects([obj1, obj2], function(objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
objects.forEach(function(o) {
canvas.add(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});
这篇关于在Fabric.js中反序列化JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!