首页 > 解决方案 > 在Typescript中子类化Fabric JS类型反序列化时导致错误

问题描述

我扩展了 Fabric Js 默认类型:


export class Button extends fabric.Rect {


  public text: string;
  public textColor: string;
  public font = '30px Arial';
  public action: ActionEnum;
  public type = 'button';


  constructor(options: IButttonOptions) {
    super(options);
    if (options.font) {
      this.font = options.font;
    }
    this.text = options.text;
    this.textColor = options.textColor;
    this.action = options.action;
  }


  toDatalessObject(propertiesToInclude?: string[]): any {
    propertiesToInclude = (propertiesToInclude || []).concat(
      ['text', 'textColor', 'font', 'action']
    );

    return super.toDatalessObject(propertiesToInclude);
  }


  _render(ctx: CanvasRenderingContext2D) {
    super._render(ctx);
    console.log('test');
    ctx.font = this.font;
    ctx.fillStyle = this.textColor;
    ctx.textAlign = 'center';
    ctx.fillText(this.text, 0, 10);
  }

我想要像这样序列化/反序列化画布:

var json = canvas.toDatalessJSON();
canvas.clear();
canvas.loadFromJSON(json); // cause error 

但是当我想用上面定义的对象加载画布时,我有异常“klass is undefined”

我不知道如何解决这个问题。有人可以帮忙吗?

标签: javascripttypescriptfabricjs

解决方案


推荐阅读