【问题标题】:With HTML5 canvas, how to calculate the final point coordinates with an offset?使用 HTML5 画布,如何计算带有偏移量的最终点坐标?
【发布时间】:2017-07-08 19:36:22
【问题描述】:

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

非常感谢。 问候,

【问题讨论】:

    标签: javascript html5-canvas geometry


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以通过距离比率使用简单的比例: (我没有考虑圆帽)

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

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

      【讨论】:

        猜你喜欢
        • 2012-02-07
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-15
        • 2016-07-23
        • 1970-01-01
        相关资源
        最近更新 更多