向fabricjs对象添加自定义属性

Yea*_*eak 5 javascript canvas fabricjs

我试图将自定义属性添加到我有的fabric js对象:

var trimLine = new fabric.Rect({
    width: Math.round(obj.box_dimensions.box.width,2),
    height: Math.round(obj.box_dimensions.box.height,2),
    strokeWidth: 1,
    stroke: 'rgb(255,2,2)',
    fill: '',
    selectable: false
});
Run Code Online (Sandbox Code Playgroud)

所以,我的矩形我试图添加,我想在其中传递一个名称或ID,以便能够在以后获取画布对象并将其转换为json时识别它.

我试过了

var trimLine = new fabric.Rect({
    width: Math.round(obj.box_dimensions.box.width,2),
    height: Math.round(obj.box_dimensions.box.height,2),
    strokeWidth: 1,
    stroke: 'rgb(255,2,2)',
    fill: '',
    selectable: false,
    name: trimLine
});

canvas.add(trimLine);
canvas.renderAll();
Run Code Online (Sandbox Code Playgroud)

它也没用,我也试过

 trimline.name = 'trimLine'
Run Code Online (Sandbox Code Playgroud)

mar*_*rkE 5

name:trimLine应该是name:"trimLine"除非你先前声明过var trimLine='myTrimLineName'.

FabricJS有许多附加属性,包括name属性.

要避免覆盖这些本机属性,请添加子属性以指示这些是您自己的自定义属性:

// example: using .my to hold your own custom properties
trimLine.my.name='trimLine';
trimLine.my.id='myOwnID15';
trimLine.my.sayName=function(){alert(this.my.name);}
Run Code Online (Sandbox Code Playgroud)


Yea*_*eak 5

对于那些遇到同样问题的人,我解决这个问题的方法是执行以下操作:

            var trimLine = new fabric.Rect({
                width: Math.round(obj.box_dimensions.trimbox.width,2),
                height: Math.round(obj.box_dimensions.trimbox.height,2),
                strokeWidth: 1,
                stroke: 'rgb(255,2,2)',
                fill: '',
                selectable: false
            });
Run Code Online (Sandbox Code Playgroud)

在它的正下方我添加了这个代码:

           trimLine.toObject = function() {
                return {
                    name: 'trimline'
                };
            };

      canvas.add(trimLine);
      canvas.renderAll();
Run Code Online (Sandbox Code Playgroud)

所以现在当我将画布转换为 json 时,trimline 对象只返回我需要的名称。当然,您也可以添加您需要的任何其他信息。


Mic*_*hel 5

如果您的自定义属性位于变量内部,找到了一个简单的解决方案,

var oText = new fabric.IText(text, { 
    left: 100, 
    top: 100 ,
    transparentCorners: false
    });

var attribute = 'my_attribute';
var value = 'first_name';

oText[attribute] = value;

canvas.add(oText);
canvas.renderAll();
Run Code Online (Sandbox Code Playgroud)