javascript - 在 HTML5 Canvas 中沿着等式绘制直线

标签 javascript canvas html5-canvas

我在 Canvas 上有一条线 [从 (x1, y1) 到 (x2, y2)],就像一把枪。我想让子弹沿着线(枪)的方向行进。让子弹也成为一条线。我知道从 x1、y1 和 x2、y2 我可以找到线 m 的斜率和 y 截距 b。我也知道直线方程是 y = mx + b。我想让子弹沿着等式 y = mx + b 行进。


我不希望我的子弹看起来像一条从枪尾一直到 Canvas 边界的长线。我希望它是一条沿着方程 y = mx + b 重画多次的小线。


有人可以指导我如何绘制子弹的运动吗?提前致谢!

最佳答案

您可以使用一个简单的插值公式,通过调整因子 f 来设置动画。

公式为(仅针对 x 显示):

x = x1 + (x2 - x1) * f

关于如何实现的示例 -

AN ONLINE DEMO

/// 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 对的旧值并在该值和当前值之间绘制一条线,或者不太理想,单独计算位置,甚至计算 Angular 和使用固定长度。

另外值得注意的是:队伍越长,子弹飞得越快。您可以根据长度(未在演示中显示)计算 f 的增量值来解决此问题。

关于javascript - 在 HTML5 Canvas 中沿着等式绘制直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18775787/

相关文章:

javascript - jQuery 文档就绪无论我怎么写都无法工作

javascript - 使用提交按钮提交到同一表单并使用值运行 SQL 查询

javascript - jquery addClass/removeClass 不适用于 header

javascript - 使用 Canvas 在嵌套圆圈中添加文本?

canvas - 在 JavaFX 中使用 MouseEvent 和 MouseClicked 选择并移动 Canvas 图像

javascript - 如何在 PhantomJS 中使用 DOMParser?

javascript - onkeyup 和 onkeydown 没有捕捉到任何东西

javascript - 球与球弹性碰撞 : ball bounces in an unequal proportion

javascript - 如何用图像填充html5 Canvas 网格方 block ?

canvas - 为什么不赞成使用context2d.backingStorePixelRatio?