Fabric.js - 自定义 Fabric.Image class 不适用于 "loadFromJSON">"fromObject"

Fabric.js - customized Fabric.Image class don't work at "loadFromJSON">"fromObject"

我想将自定义的 Fabric.Image class 保存为 JSON,然后使用 loadFromJSON.

恢复它

我查过以下问题 Fabric.js - how to save canvas on server with custom attributes 不过好像"fromObject"的部分不太顺利

当您在以下WEB 页面上按'Click' 按钮时会发生这种情况。 https://onoderayuuki.github.io/tana_motif/index.html

[子class]

 fabric.customMotif = fabric.util.createClass(fabric.Image, {
  type: 'customMotif',
  borderColor: '#19310B',
  cornerColor: '#19310B',
  cornerSize: 20,

 initialize: function(src, options) {
   this.callSuper('initialize', options);
   options && this.set('name', options.name);
   this.image = new Image();
   this.top = options.top;
   this.left = options.left;
   this.image.src = src;
   this.image.onload = (function() {
     this.width = this.image.width;
     this.height = this.image.height;
     this.loaded = true;
     this.setCoords();
     this.fire('image:loaded');
   }).bind(this);
 },

  toObject: function(options) {
       return fabric.util.object.extend(this.callSuper('toObject'), {
       });
  },
  _render: function(ctx) {
   if (this.loaded) {
      ctx.drawImage(this.image, -this.width / 2, -this.height / 2);
   }
  }
});

fabric.customMotif.fromObject = function(object, callback) {
  fabric.util.loadImage(object.src, function(img) {
    callback && callback(new fabric.customMotif(img, object));
  });
};

[JSON]

  canvasState = JSON.stringify(canvas);
  canvas.loadFromJSON(canvasState);

谢谢。

如果你检查这个函数,你会发现 class 的第一个字母是大写的。

getKlass: function(type, namespace) {
  // capitalize first letter only
  type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
  return fabric.util.resolveNamespace(namespace)[type];
},

将 class 从 fabric.customMotif 重命名为 fabric.CustomMotif