canvas 乒乓球闪闪发光

canvas ping pong sparkles

我正在尝试为我的基本乒乓球比赛增添火花。每当球击中桨时,都应添加火花。我正在用

创建火花作为对象
function create_sparks(x, y, m) {
    this.x = x;
    this.y = y;
    this.r = 1,2;
    this.vx = -1.5 + Math.random() * 3;
    this.vy = m * Math.random() * 1.5;
}

我正在像这样创建它们

if (flag == 1) {
        for (var j = 0; j < 20; j++) {

            particles.push(new create_sparks(spark.x, spark.y, mult));
        }
    }
    emitspark();
    flag = 0;

当球击中水坑时,标志为 1,spark.x 和 spark.y 是球的来源(它击中水坑的地方),最后我像这样制作动画

function emitspark() {
    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
        ctx.beginPath();
        ctx.fillStyle = "white";
        if (p.r > 0) {
            ctx.arc(p.x, p.y, p.r, 0, Math.Pi * 2);
        }
        ctx.fill();
        p.x+=p.vx;
        p.y+=p.vy;
        p.r=Math.max(p.r-0.05,0.0);
    }
}

问题是,火花不会出现,代码也不会抛出任何错误并且工作正常(只是没有火花)我是否忽略了什么? here 是演示

主要问题是 ball.h 未定义 - 它为 spark.y 个值生成一个 NaN 值。

ball = {
    x: 50,
    y: 50,
    r: 5,
    h: 10, // < ---- NEW
    c: "white",
    vx: 4,
    vy: 8,

    // Function for drawing ball on canvas
    draw: function () {
       ctx.beginPath();
       ctx.fillStyle = this.c;
       ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
       ctx.fill();
       update();
    }
};

修复了这个问题。在探索代码时,我还更改了 emitspark() 。随心所欲地简化,但这个版本对我有用:

function emitspark() {
    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
            ctx.beginPath();
            ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
            ctx.lineWidth = 15;
            ctx.strokeStyle = 'red';
            ctx.fillStyle="white";
            ctx.fill();
            ctx.stroke();
        p.x+=p.vx;
        p.y+=p.vy;
        p.r=Math.max(p.r-0.05,0.0);
    }
}

最后,我建议在火花效果结束后将粒子阵列长度设置为零,以防止阵列变得越来越长。零半径火花仍在处理中——人们假设上下文弧方法根本没有为它们创建路径。但是闪闪发光!