在HTML5画布中绘制一条直线的方程式

3
我在画布上有一条线段(从(x1,y1)到(x2,y2)),它像一把枪一样。我希望子弹沿着这条线段(即枪口方向)飞行。让子弹也是一条线段。我知道通过x1,y1和x2,y2可以找到线段的斜率m和y轴截距b。我也知道线段的方程式是y = mx + b。我想让子弹沿着方程式y = mx + b移动。
我不想让我的子弹看起来像一条长长的线段,从枪口一直延伸到画布的边缘。我希望它是一条小线段,多次重绘沿着方程式y = mx + b移动。
请问有人能指导我如何绘制子弹的运动吗?提前感谢!

1
这个链接是Mozilla开发者网络上的HTML Canvas教程,希望对你有所帮助。 - user2672373
1个回答

3

您可以使用简单的插值公式,通过调整因子 f 来对其进行动画处理。

该公式为(仅用于x):

x = x1 + (x2 - x1) * f

一个关于如何实现的例子 - 在线演示
/// add click callback for canvas (id = demo)
demo.onclick = function(e) {

    /// get mouse coordinate
    var rect = demo.getBoundingClientRect(),

        /// gun at center bottom
        x1 = demo.width * 0.5,
        y1 = demo.height,

        /// target is where we click on canvas
        x2 = e.clientX - rect.left,
        y2 = e.clientY - rect.top,

        /// factor [0, 1] is where we are at the line
        f = 0,

        /// our bullet
        x, y;

    loop();
}

然后我们提供以下代码用于循环。
function loop() {

    /// clear previous bullet (for demo)
    ctx.clearRect(x - 2, y - 2, 6, 6);

    /// HERE we calculate the position on the line
    x = x1 + (x2 - x1) * f;
    y = y1 + (y2 - y1) * f;

    /// draw some bullet
    ctx.fillRect(x, y, 3, 3);


    /// increment f until it's 1
    if (f < 1) {
        f += 0.05;
        requestAnimationFrame(loop);
    } else {
        ctx.clearRect(x - 2, y - 2, 6, 6);
    }

}

为了绘制一个沿着线路“更长”的子弹,您可以存储x/y对的旧值并在当前值之间绘制一条线,或者更不理想的是,单独计算位置甚至计算角度并使用固定长度。此外,值得注意的是:线条越长,子弹速度越快。您可以根据长度(演示中未显示)计算f的增量值来解决这个问题。

太棒了!非常感谢Ken,这非常有教育意义。让我试一下并理解它。 - SerotoninChase

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接