简体   繁体   English

在HTML5 Canvas中绘制一条线的等式

[英]Drawing along an equation of a line in HTML5 Canvas

I have a line [from (x1, y1) to (x2, y2)] on the canvas that acts like a gun. 我在画布上有一条[从(x1,y1)到(x2,y2)]的线,就像一把枪。 I want the bullet to travel in the direction of the line (gun). 我希望子弹朝着直线方向(枪)行进。 Let the bullet also be a line. 让子弹也成一条线。 I know that from x1, y1 and x2, y2 I can find the slope of the line m and the y-intercept b. 我知道从x1,y1和x2,y2我可以找到m行和y截距b的斜率。 I'm also aware that the equation of a line is y = mx + b. 我也知道一条线的方程是y = mx + b。 I want the bullet to travel along the equation y = mx + b. 我希望子弹沿等式y = mx + b行进。


I do not want my bullet to look like a long line that starts from the end of my gun all the way to the boundary of the canvas. 我不希望我的子弹看起来像一条长长的线,从我的枪的末端一直到画布的边界。 I want it to be a small line redrawn multiple times along the equation y = mx + b. 我希望它是沿着等式y = mx + b多次重绘的小线。


Can someone please guide me on how to draw my bullet's movement? 有人可以指导我如何绘制子弹的动作吗? Thanks in advance! 提前致谢!

You can use a simple interpolation formula where you animate it by adjusting the factor f . 您可以使用简单的插值公式,通过调整因子f为其设置动画。

The formula is (shown only for x ): 公式是(仅显示x ):

x = x1 + (x2 - x1) * f

An example on how to implement - 关于如何实施的一个例子 -

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

Then we provide the following code for the 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);
    }

}

To draw a "longer" bullet that follows the line you can either store an older value of the x/y pair and draw a line between that and current, or less optimal, calculate the position separately or even calculate the angle and use a fixed length. 要在线后面绘制一个“更长”的子弹,您可以存储x / y对的较旧值并在该值和当前值之间绘制一条线,或者不太理想,单独计算位置或甚至计算角度并使用固定的长度。

Also worth to be aware of: the longer the line is the faster the bullet goes. 另外值得注意的是:线越长,子弹越快。 You can calculate a delta value for f based on length (not shown in demo) to get around this. 您可以根据长度(未在演示中显示)计算f的delta值以解决此问题。

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

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