2017-07-08 35 views
0

在HTML5畫布對象上,我必須減去距離目標點的距離,以便在同一行上給出最終目標。因此,首先我已經用畢達哥拉斯定理計算了源點和目標點之間的距離,但是我對泰勒斯定理的記憶太錯誤了,找不到最終點(在同一條線上),右邊的x和y屬性。使用HTML5畫布時,如何用偏移量計算最終點座標?

function getDistance (from, to){ 
    return Math.hypot(to.x - from.x, to.y - from.y); 
} 
function getFinalTo (from, to, distanceToSubstract){ 

    //with Pythagore we obtain the distance between the 2 points 
    var originalDistance = getDistance(from, to); 
    var finalDistance = originalDistance - distanceToSubstract; 

    //Now, I was thinking about Thales but all my tries are wrong 
    //Here some of ones, I need to get finalTo properties to draw an arrow to a node without 

    var finalTo = new Object; 
    finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x); 
    finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y); 

    return finalTo; 
} 

實際上,箭頭被半徑約100像素的圓形節點隱藏,所以我嘗試獲得最終點。

非常感謝。 問候,

回答

0

將取決於線帽。對於"butt",沒有變化,對於"round""square",您的線條在每一端的寬度延伸了一半

以下函數根據線條帽縮短線條以適合線條。

drawLine(x1,y1,x2,y2){ 
    // get vector from start to end 
    var x = x2-x1; 
    var y = y2-y1; 
    // get length 
    const len = Math.hypot(x,y) * 2; // *2 because we want half the width 
    // normalise vector 
    x /= len; 
    y /= len; 
    if(ctx.lineCap !== "butt"){ 
     // shorten both ends to fit the length 
     const lw = ctx.lineWidth; 
     x1 += x * lw; 
     y1 += y * lw; 
     x2 -= x * lw; 
     y2 -= y * lw; 
    } 
    ctx.beginPath() 
    ctx.lineTo(x1,y1); 
    ctx.lineTo(x2,y2); 
    ctx.stroke(); 
} 

斜切加入了以下的答案將會有助於https://stackoverflow.com/a/41184052/3877726

0

您可以通過距離比使用簡單的比例: (我沒佔到圓帽)

ratio = finalDistance/originalDistance 
finalTo.x = from.x + (to.x - from.x) * ratio; 
finalTo.y = from.y + (to.y - from.y) * ratio; 

你的方法是嘗試使用線性插值,但是你錯誤地混合距離(以像素爲單位(無量綱 - 這個詞是否正確?)

ratio = finalDistance/originalDistance 
finalTo.x = ((1 - ratio) * from.x) + (ratio * to.x); 
finalTo.y = ((1 - ratio) * from.y) + (ratio * to.y); 

請注意,這兩種方法是真的相同的公式。