使用 Angular 向 Fabric.js 对象添加自定义属性

JSm*_*ith 2 fabricjs typescript angular

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

我试过了

rect.customAttribute = value
Run Code Online (Sandbox Code Playgroud)

但这使编译陷入困境,我收到以下错误:

对象文字只能指定已知属性,并且类型“IRectOptions”中不存在“customAttribute”。

我也尝试过该功能toObject(),但无法找到我的属性并进行设置。此外,在使用toObject()然后尝试使用之前的方法设置我添加的属性之后,我在逻辑上得到了相同的错误。

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'])
Run Code Online (Sandbox Code Playgroud)

gru*_*unk 5

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

interface IRectWithId extends fabric.IRectOptions {
    id: number;
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为你的矩形的参数

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);
Run Code Online (Sandbox Code Playgroud)