向 fabricjs 对象添加自定义属性

adding custom attributes to fabricjs object

我正在尝试向我拥有的结构 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
});

这就是我试图添加的矩形,我想在其中传递一个名称或 ID,以便稍后在我获得 canvas 对象并将其转换为 [=22= 时能够识别它].

我试过

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();

没用我也试过

 trimline.name = 'trimLine'

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);}

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

            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
            });

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

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

      canvas.add(trimLine);
      canvas.renderAll();

所以现在当我将 canvas 转换为 json 修剪线对象时,只有 returns 我需要的名称。当然,您也可以添加您需要的任何其他信息。

我知道它很旧,但这适用于版本 2.2.3

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
            });

let obj={hello:'World'};
trimLine.set('helloworld',obj);

然后就可以拿到对象了

  var myObj = e.target.get('helloworld');

如果您的自定义属性在变量中,找到了一个简单的解决方案,

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();