首页 > 解决方案 > 使用 Angular 向 fabric.js 对象添加自定义属性

问题描述

正如问题中所说,我正在尝试将自定义属性添加到 Fabric.js 对象。

我试过了

rect.customAttribute = value

但这卡住了编译我收到以下错误:

对象字面量只能指定已知属性,而“IRectOptions”类型中不存在“customAttribute”。

我也试过这个功能toObject(),但找不到我的属性并设置它。同样在使用toObject()then 尝试使用以前的方法设置我添加的属性之后,我在逻辑上得到了相同的错误。

let rect = new fabric.Rect(
    {
        left:0,
        top: 0,
        width: 60
        height:60,
        fill: 'orange',
        selectable: true,
        evented: true,
        name: 'rect',
        cornerColor:'red',
        cornerSize:5,
        borderColor:'red',
        borderScaleFactor: 5,
        noScaleCache:false,
        customAttribute:false
    })
rect.toObject(['customAttribute'])

标签: angulartypescriptfabricjs

解决方案


您可以简单地创建一个从原始接口继承的接口。例如,如果我想将 id 添加到矩形:

interface IRectWithId extends fabric.IRectOptions {
    id: number;
}

然后将其用作矩形的参数

const opt = {
    left: left,
    top: top,
    strokeWidth: 1,
    width: width,
    height: height,
    fill: 'rgba(98,98,98,0.8)',
    stroke: 'rgba(98,98,98,1)',
    hasControls: true,
    id: this.masks.length
} as IRectWithId;

const rect = new fabric.Rect(opt);

推荐阅读