2017-02-21 115 views
0

我試圖在移動時獲取對象的x和y座標。我在object:moving上使用getLeft()getTop()方法。但是,如果對象旋轉,這些方法不起作用。移動時更新fabricjs對象座標

然後我嘗試使用object.getBoundRect().top獲取對象邊界框的頂部和左側。但是這不會動態更新。它在移動操作開始時給出邊界框的值。有沒有辦法在移動時獲得邊界框的值?

canvas.on('object:moving', function(e) { 
    var scaledObject = e.target; 
    $('#mouse-info').text("X:"+parseInt(scaledObject.getBoundingRect().left)+", Y:"+parseInt(scaledObject.getBoundingRect().top)); 
}); 

回答

0

薩米,

你正在做的事情是錯誤的。共達和getLeft做工精細的1.7版本

檢查這個代碼:

canvas.on('object:moving',function(e){ 
    if (e.target){ 
     console.log(e.target.getTop()); 
     console.log(e.target.getLeft()); 
    } 
}); 

UPDATE:

如果你想有旋轉你以後每次做渲染:

canvas.on('after:render', function() { 
    canvas.contextContainer.strokeStyle = '#555'; 
    canvas.forEachObject(function(obj) { 
     var bound = obj.getBoundingRect(); 
     canvas.contextContainer.strokeRect(
     bound.left + 0.5, 
     bound.top + 0.5, 
     bound.width, 
     bound.height 
    ); 
    }); 

    var ao = canvas.getActiveObject(); 
    if (ao) { 
    var bound = ao.getBoundingRect(); 
    console.log(bound.left); 
    console.log(bound.top); 
    } 
    }); 

此代碼將爲每個渲染後的每個形狀繪製邊界框。如果你想隱藏邊框刪掉這些代碼:

canvas.contextContainer.strokeStyle = '#555'; 
     canvas.forEachObject(function(obj) { 
      var bound = obj.getBoundingRect(); 
      canvas.contextContainer.strokeRect(
      bound.left + 0.5, 
      bound.top + 0.5, 
      bound.width, 
      bound.height 
     ); 
     }); 

這裏是一個fiddle

希望,它會幫助你。

+0

它不適用於旋轉的對象。 – Sammy

+0

我仍然得到輸出。但是由於旋轉時對象的左側發生了變化,所以這是不正確的。 – Sammy

+0

檢查更新的帖子。我做了更新,而不是使用對象:render:render後使用 – Observer