我试图将自定义属性添加到我有的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
});
所以,我的矩形我试图添加,我想在其中传递一个名称或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();
它也没用,我也试过
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();
所以现在当我将画布转换为json时,trimline对象只返回我需要的名称。当然,您也可以添加您需要的任何其他信息。
如果您的自定义属性在变量中,找到一个简单的解决方案,
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();
我知道它已经过时但这适用于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');