简体   繁体   中英

How to animate a ball becoming smaller in HTML5 canvas

I'm trying to make a ball become increasingly smaller using HTML5 canvas. I've been able to make it grow larger, so I figured the reverse would be simple. What am I doing wrong here? Console.log shows me values from 11 to 0 decreasing by 1. When x is less than 0, it stops. But the ball doesn't change shape, and I suspect its because it's drawing smaller shapes on top of each other, perhaps? I thought clearRect would work for that?

function draw2()
{
    console.log(x);
    context2D.clearRect(0, 0, canvas.width, canvas.height);
    context2D.arc(10, 10, x, 0, Math.PI * 2, true);
    context2D.fill();
    x -= 1;
    if (x < 0) {
        clearInterval(s);   
    }
}

A demo is available at: http://www.chronicled.org/dev/test.html

Thanks!

add context2D.beginPath(); to the beginning of draw2 (it also wouldn't hurt to have it in draw)

the .fill is filling the whole path which includes the old arcs

The fill() call is filling the old rect again. Try this instead:

function draw2()
{
    console.log(x);     
    context2D.clearRect(0, 0, canvas.width, canvas.height);

     context2D.beginPath();
     context2D.arc(15, 15, x, 0, Math.PI * 2, true);
     context2D.fill();
     context2D.closePath();
    x -= 1;
    if (x < 0) {
        clearInterval(s);   
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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