我有一个矩形和一个文本对象。我希望当我将“文本”拖到画布上时,它能跟随“矩形”
2017-06-02
261
fabric.Canvas.prototype.getItemsByName = function(name) {
var objectList = [],
objects = this.getObjects();
for (var i = 0, len = this.size(); i < len; i++) {
if (objects[i].name && objects[i].name === name) {
if (objects[i].type && objects[i].type === "text") {
objectList.push(objects[i]);
}
}
}
return objectList;
};
var moveHandler = function (evt) {
var movingObject = evt.target;
//console.log(movingObject.get('left'), movingObject.get('top'));
var textToMove = canvas.getItemsByName(objectname);
textToMove.style.left = movingObject.get('left')+'px';// 'px';
textToMove.style.top = movingObject.get('top')+'px';// 'px';
};
canvas.on('object:moving', moveHandler);
上面的代码找到了文本对象,但仍然没有使文本移动到其后面。我做错了什么?
我正在使用 fabric.js。
画布上有两个对象。当我使用事件时,我可以在控制台中看到移动对象的坐标。而且我还可以得到我想要跟随矩形的文本对象存在的证明
(var textToMove = canvas.getItemsByName(objectname));
但是...我得到了下一个
Uncaught TypeError: Cannot set property 'left' of undefined next to: textToMove.style.left = movingObject.get('left')+'px';
哪里错了?
var circle1 = new fabric.Circle({
radius: 10,
fill: 'green',
left: 100,
top: 100,
id:objectname+"Circle" ,
name:objectname
});
var text40 = new fabric.Text(objectname, {
selectable :false,
left:100,
top: 80,
fontWeight: 'bold',
fontSize: 12,
id:objectname+"Text",
name:objectname
});
2个回答
如果文本是要移动的元素的子元素,只需将其
position
设置为
relative
。而不是尝试计算要将其移动到的像素。
jdmdevdotnet
2017-06-02
fabric.Canvas.prototype.getItemByName2 = function(objectname) {
var object = null,
objects = this.getObjects();
for (var i = 0, len = this.size(); i < len; i++) {
if (objects[i].type && objects[i].type === "text"){
if (objects[i].name && objects[i].name=== objectname) {
object = objects[i];
break;
}
}
}
return object;
};
var moveHandler = function (evt) {
var movingObject = evt.target;
var leftx = movingObject.get('left');
var topy = movingObject.get('top');
canvas.getItemByName2(objectname).set('left',leftx);
canvas.getItemByName2(objectname).set('top',topy-20);
};
canvas.on('object:moving', moveHandler);
因为这是有效的。 谢谢
2017-06-08