简体   繁体   中英

JavaScript - Animated shapes behave strange in HTML5 <canvas>

I have a small univrsity project. I am animating circles using <canvas> element. They appear from bottom border and smoothly move up. X coordinate, radius and color of circles are choosen randomly.

The problem is that when my circles reach upper border of <canvas> they start to blink and sometimes change their color. Here's the JSFIDDLE . What am i doing wrong? Thanks.

for...in is great for iterating over objects, but it's not designed for iterating over arrays. In essence, your i is jumping around a bit. Instead of using for...in , use this (very efficient) loop:

for(var i = circles.length; i--;) {

That solves the problem!

Sometimes the blinking happens because there are circles on top of other circles. More often, however, it's because you're altering the list while looping through it.

If you instead keep track of the circles to remove, and then remove them after drawing the circles, it looks better:

function animateCircles() {
    if(frameCounter % 4 === 0) addCircle();
    var remove = [];
    for(var i = 0; i < circles.length; ++i) { // DON'T USE for ... in on an array!
        circles[i]['y'] -= 2;
        drawCircle(circles[i]['x'], circles[i]['y'], circles[i]['r'], circles[i]['c']);
        if(circles[i]['y'] < -circles[i]['r']) remove.push(i);
    }
    for (i = remove.length; --i >= 0; )
        circles.splice(remove[i], 1);
}

Forked fiddle.

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