首页 > canvas问题

canvas问题

绘制圆球匀速下落时每一次的速度比上一次更快,越来越快,不知道问题出在哪里。求解,谢谢各位了。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var ball =
{
    x:0,
    y:0,
    r:15,
    vy:12,
    vx:12
}

var drawCircle = function (x,y,r,color)
{
    context.clearRect(0,0,canvas.width,canvas.height);
    context.lineWidth = '5';
    context.beginPath();
    context.arc(x,y,r,0,Math.PI*2,false);
    context.strokeStyle = 'rgba(120,150,170,0.5)';
    context.fillStyle = color;
    context.closePath();
    context.stroke();
    context.fill();
}

var  update = function ()
{
    ball.y +=ball.vy;
    if (ball.y >= canvas.height - ball.r)
    {
        ball.y = canvas.height - ball.r;
        ball.x -= ball.vx;
    }
}

this.onclick = function (event)
{
    ball.x = event.clientX;
    ball.y = event.clientY;

    setInterval(function ()
    {
        drawCircle(ball.x,ball.y,ball.r,'blue');
        update();
    },100);
}

每次点击都创建了一个定时器,从第2次点击开始,已经不是1个定时器在执行 update 了。

var timer;
this.onclick = function (event)
{
    ball.x = event.clientX;
    ball.y = event.clientY;
    
    timer = setInterval(function ()
    {
        drawCircle(ball.x,ball.y,ball.r,'blue');
        update();
    },100);
}

var  update = function ()
{
    ball.y +=ball.vy;
    if (ball.y >= canvas.height - ball.r)
    {
        ball.y = canvas.height - ball.r;
        ball.x -= ball.vx;
    }
    
    if(...) {
       clearInterval(timer)
    }
}

满足某种条件,比如运动完毕后,记得清除定时器。

【热门文章】
【热门文章】