我有一个矩形和一个文本对象。我想" text"遵循"矩形"当我把他拖到画布上时

时间:2017-06-02 22:05:45

标签: javascript fabricjs

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

但是......我接下来

  

未捕获的TypeError:无法设置属性&#39; left&#39;未定义的旁边:   textToMove.style.left = movingObject.get(&#39; left&#39;)+&#39; px&#39;;

有什么问题?

  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 个答案:

答案 0 :(得分:0)

如果文字是要移动的元素的子代,只需将其position设置为relative即可。而不是试图计算像素来移动它。

答案 1 :(得分:0)

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

因为这是有效的。 谢谢