我在fabric.js中有一个“双面”画布。它们都是从JSON字符串加载的。 我有一个功能,使画布适合窗口大小,也可以调整每个对象的大小。问题是当其中一个JSON中存在imageblob时,加载需要更多时间。因此,当我调用我的函数时,我最终得到一个画布上的所有对象而另一个画布上没有。我做了一个setTimeout,但这不是最好的解决方案。如何在没有settimeout的情况下同时调整所有内容的大小?这是我的功能
function fitWindow(){
var windowWidth = $("#wrapper").innerWidth();
var originalWidth = canvas.getWidth();
var originalHeight = canvas.getHeight();
var newWidth = windowWidth-30;
var newHeight = (originalHeight / originalWidth)* newWidth;
canvas.setWidth(newWidth);
canvas.setHeight(newHeight);
var myScale = originalWidth/newWidth;
var objects = canvas.getObjects();
for (var i in objects) {
var scaleX = objects[i].get('scaleX');
var scaleY = objects[i].get('scaleY');
var left = objects[i].get('left');
var top = objects[i].get('top');
var tempScaleX = scaleX * (1 / myScale);
var tempScaleY = scaleY * (1 / myScale);
var tempLeft = left * (1 / myScale);
var tempTop = top * (1 / myScale);
objects[i].set('scaleX',tempScaleX);
objects[i].set('scaleY',tempScaleY);
objects[i].set('left',tempLeft);
objects[i].set('top',tempTop);
objects[i].setCoords();
}
canvas.renderAll();
var ojS = canvas.toObject(['name']);
var savedCanvas = JSON.stringify(ojS);
canvas.clear();
canvas.loadFromJSON(canvas2, canvas.renderAll.bind(canvas));
setTimeout(function(){
var objects2 = canvas.getObjects();
for (var k in objects2) {
var scaleX2 = objects2[k].get('scaleX');
var scaleY2 = objects2[k].get('scaleY');
var left2 = objects2[k].get('left');
var top2 = objects2[k].get('top');
var tempScaleX2 = scaleX2 * (1 / myScale);
var tempScaleY2 = scaleY2 * (1 / myScale);
var tempLeft2 = left2 * (1 / myScale);
var tempTop2 = top2 * (1 / myScale);
objects2[k].set('scaleX',tempScaleX2);
objects2[k].set('scaleY',tempScaleY2);
objects2[k].set('left',tempLeft2);
objects2[k].set('top',tempTop2);
objects2[k].setCoords();
}
canvas.renderAll();
var ojS2 = canvas.toObject(['name']);
canvas2 = JSON.stringify(ojS2);
canvas.clear();
canvas.loadFromJSON(savedCanvas, canvas.renderAll.bind(canvas));
canvas.renderAll();
},100);
}
答案 0 :(得分:1)
好的,我想我找到了解决方案。我将函数绑定到JSON加载的回调,如下所示:
canvas.loadFromJSON(canvas2, function() {
scaleObjects(scale,canvas.getObjects());
canvas2 = savedCanvasJSON(canvas.toObject(['name']));
canvas.clear();
canvas.loadFromJSON(savedCanvas, canvas.renderAll.bind(canvas));
});
它按预期工作