如何在每次调用draw函数后防止对象位置呈指数级增加



简单的动画,每次单击都会在画布上创建类似烟花的效果。问题是动画是用setInterval(绘制)制作的,每次重新绘制画布时,每个粒子的位置都是+=particle.speed。但每次单击时,粒子移动得越来越快,因为每个粒子的速度似乎都没有重置。

正如你在这里的工作示例上点击几下可以看到的那样:第一次点击时,粒子移动非常(正确)缓慢,但每次点击后,速度都会增加。

使用的JS也粘贴在下面,任何帮助都将不胜感激!

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    canvas.addEventListener("click", startdraw, false);

    //Lets resize the canvas to occupy the full page
    var W = window.innerWidth;
    var H = window.innerHeight;
    canvas.width = W;
    canvas.height = H;

    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, W, H);
    //global variables
    var radius;
    radius = 10;
    balls_amt = 20;
    balls = [];
    var locX = Math.round(Math.random()*W);
    var locY = Math.round(Math.random()*H);

    //ball constructor
    function ball(positionx,positiony,speedX,speedY)
    {   
        this.r = Math.round(Math.random()*255);
        this.g = Math.round(Math.random()*255);
        this.b = Math.round(Math.random()*255);
        this.a = Math.random();
        this.location = {
            x: positionx,
            y:positiony
        }
        this.speed = {
            x: -2+Math.random()*4, 
            y: -2+Math.random()*4
        };
    }


    function draw(){
        ctx.globalCompositeOperation = "source-over";
        //Lets reduce the opacity of the BG paint to give the final touch
        ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
        ctx.fillRect(0, 0, W, H);
        //Lets blend the particle with the BG
        //ctx.globalCompositeOperation = "lighter";
        for(var i = 0; i < balls.length; i++)
        {
            var p = balls[i];
            ctx.beginPath();
            ctx.arc(p.location.x, p.location.y, radius, Math.PI*2, false);
            ctx.fillStyle = "rgba("+p.r+","+p.g+","+p.b+", "+p.a+")";
            ctx.fill(); 
            var consolelogX = p.location.x;
            var consolelogY = p.location.y;
            p.location.x += p.speed.x;  
            p.location.y += p.speed.y;

        }
    }
    function startdraw(e){
        var posX = e.pageX;     //find the x position of the mouse
        var posY = e.pageY;     //find the y position of the mouse
        for(i=0;i<balls_amt;i++){
            balls.push(new ball(posX,posY));
        }
        setInterval(draw,20);
        //ball[1].speed.x;
    }   

每次单击后都会调用startdraw,每次对draw方法进行新的定期调用(setInterval)时都会启动。因此,在第二次单击后,您有2个平行间隔,在第三次单击后您有3个平行间隔。它不是指数增长的,只是线性增长的:)

一个可能的脏修复:引入interval全局变量,并替换此行:

         setInterval(draw,20);

这个:

        if (!interval) interval = setInterval(draw,20);

或者一个更好的解决方案是在onLoad事件开始间隔。

setInterval将每隔20毫秒重复一次调用,并返回一个ID。您可以通过调用clearInterval(ID)来停止重复。

var id = setInterval("alert('yo!');", 500);
clearInterval(id);

最新更新