2017-07-08 5 views
0

HTML5キャンバスオブジェクトでは、最終的な宛先を同じ行に与えるために、宛先点から距離を引く必要があります。HTML5キャンバスで、オフセットを使って最終点の座標を計算する方法は?

まず、ピタゴラスの定理を使って、原点と目標点の距離を計算しましたが、タレスの定理の記憶は、同じ点の上にある最終点(右のxとy)属性。

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

どちらのアプローチも実際には同じ式です。

関連する問題