繁体   English   中英

使用HTML5 canvas,如何计算带偏移的最终点坐标?

[英]With HTML5 canvas, how to calculate the final point coordinates with an offset?

在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像素的圆形节点隐藏,因此我尝试获得最终点。

非常感谢。 问候,

您可以按距离比例使用简单的比例:(我没有考虑圆形上限)

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

请注意,这两种方法实际上是相同的公式。

将取决于线帽。 对于"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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM