保存使用 fabric.js 创建的 canvas

Save canvas created with fabric.js

我想存储用 fabric.js 生成的 canvas,我的页面 canvas 如下所示

 <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 文档所述 serialization 试图将 canvas 保存为 json,但无法获取 canvas 中的对象它总是 returns 为空,如下所示

{"objects":[],"background":""}

我生成 json 的代码如下

var canvas = new fabric.Canvas('design-stage');
console.log(canvas);
var json = JSON.stringify( canvas.toJSON()  );
console.log(json);

用于在 canvas

上添加图像的代码
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 图像并通过定位图像

将这些图像添加到 canvas

fabric.Image.fromURL 在里面做了一些 异步 的事情。您的代码中的 回调 (function (img) { ... }) 将在图像加载后被调用。虽然我看不到其余代码,但我确定您是在调用 fabric.Image.fromURL 之后立即调用 JSON.stringify(canvas) 而不是 等待 异步图像加载完成。

试试这个:

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') 输出一个空的 canvas 而 foo.debug('2') 输出一个添加图像的地方。自己试试看 here.

在第一个 debug 调用中 function (url) { ... } 尚未被 fabric.Image.fromURL 调用,因此 canvas 为空。您需要等待它被调用,就像任何其他 AJAX request/callback 一样。 因此 任何 依赖于要加载的图像的代码都必须从该回调中调用。