我想存储用fabric.js生成的画布,我的页面如下所示
<div class="canvas-container" style="width: 600px; height: 600px; position: relative; -moz-user-select: none;">
<canvas height="600" width="600" id="design-stage" class="lower-canvas" style="position: absolute; width: 600px; height: 600px; left: 0px; top: 0px; -moz-user-select: none;"></canvas>
<canvas class="upper-canvas " style="position: absolute; width: 600px; height: 600px; left: 0px; top: 0px; -moz-user-select: none; cursor: default;" width="600" height="600"></canvas>
</div>
如fabric.js文档中所述,序列化试图将画布另存为json,但是无法获取画布中的对象,因此它总是返回空,如下所示
{"objects":[],"background":""}
和我生成json的代码如下
var canvas = new fabric.Canvas('design-stage');
console.log(canvas);
var json = JSON.stringify( canvas.toJSON() );
console.log(json);
在画布上添加图像的代码
self._loadItemImage = function (url) {
fabric.Image.fromURL(url, function (img) {
var w = img.width; var h = img.height;
var size = self._resizeImage(w, h, self._width - 100, self._height - 100);
img.set({ left: self._width / 2, top: self._height / 2, originX: 'center', originY: 'center', hasBorders: false, hasControls: false, hasRotatingPoint: false, selectable: false, scaleX: 0.5, scaleY: 0.5 });
self._motorImg = img;
self._canvas.add(self._motorImg);
});
};
注意:不是使用fabric.js中的函数创建的对象,我已经从目录加载了svg图像,并通过放置图像将这些图像添加到画布中
fabric.Image.fromURL
在里面做一些异步的事情。加载图像后,将调用代码中的回调(function (img) { ... }
)。尽管我看不到其余的代码,但是我确定您在调用后立即调用了该函数,并且没有等待异步图像加载完成。JSON.stringify(canvas)
fabric.Image.fromURL
试试这个:
function Foo() {
var self = this;
self._motorImg = null;
self._canvas = new fabric.Canvas('c');
self._loadItemImage = function (url) {
fabric.Image.fromURL(url, function (img) {
img.set({ left: 0, top: 0, originX: 'center', originY: 'center' });
self._motorImg = img;
self._canvas.add(self._motorImg);
self.debug('2');
});
};
self.debug = function (when) {
console.log(when, JSON.stringify(self._canvas));
};
}
var foo = new Foo();
foo._loadItemImage('http://jsfiddle.net/img/logo.png');
foo.debug('1');
您肯定会注意到,foo.debug('1')
输出一个空白画布,而foo.debug('2')
输出一个添加了图像的画布。在这里自己尝试。
第一次debug
调用function (url) { ... }
尚未由调用fabric.Image.fromURL
,因此画布为空。您需要等待它被调用,就像其他任何AJAX请求/回调一样。因此,取决于要加载的图像的任何代码都必须从该回调中调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句