【fabric.js】创建属于自己的图形类

179 阅读1分钟

创建属于自己的图形类

/**
 * @description 对 fabric.Object 原型继承的简单抽象
 * @param { parentopt } 需要继承的类
 * @param { propertiesopt } 此类的所有实例共享的属性
 */
fabric.util.createClass(parentopt, propertiesopt) => object

propertiesopt 参数说明

这个参数是用来描述自定义类的所有实例共享的属性。这里需要注意以下内容:

  • initialize: 用于初始化, 接收实例化时传进来的参数
  • callSuper: 在子类中继承父类的方法
  • _render: 可以自定义渲染

使用示例

场景

创建一个文本标签

fabric 实现的逻辑分析

这里因为想写一个稍微复杂一点的例子,所以使用的是Group。如果想要简单实现这个功能,可以使用fillText属性。下面是步骤的逐步分析:

  1. 创建一个矩形
  2. 创建一个文本
  3. 组合矩形和文本,并继承组合的相关方法和属性
  4. 将自定义属性写进其它方法里,这里示例的是toObject

代码实现

const LabelRect = fabric.util.createClass(fabric.Group, {
    type: "labelRect",
    initialize: function (options = {}) {
      // 同步矩形和文本的属性,使大小位置 一致
      const defaults = {
        width: options.width || 300,
        height: options.height || 100,
        originX: "center",
        originY: "center",
      };
      // 创建一个矩形
      const rect = new fabric.Rect({
        ...defaults,
        fill: "#77AAFF",
      });
      // 创建一个文本
      const text = new fabric.Textbox(options.label, {
        ...defaults,
        textAlign: "center",
        fill: "#fff",
        fontSize: 20,
      });
      // 继承Group属性
      this.callSuper("initialize", [rect, text], options);
      // 设置label属性
      this.set("label", options.label || "");
    },
    // 继承group.toObject 方法,添加label属性
    toObject: function () {
      return fabric.util.object.extend(this.callSuper("toObject"), {
        label: this.get("label"),
      });
    },
});
var labeledRect = new LabelRect({
    width: 100,
    height: 50,
    left: 100,
    top: 100,
    label: "test",
});