简体   繁体   English

JavaScript-动画形状在HTML5中表现奇怪<canvas>

[英]JavaScript - Animated shapes behave strange in HTML5 <canvas>

I have a small univrsity project. 我有一个小型的大学项目。 I am animating circles using <canvas> element. 我正在使用<canvas>元素为圈子设置动画。 They appear from bottom border and smoothly move up. 它们从底部边框出现并平稳向上移动。 X coordinate, radius and color of circles are choosen randomly. 随机选择X坐标,圆的半径和颜色。

The problem is that when my circles reach upper border of <canvas> they start to blink and sometimes change their color. 问题是,当我的圆圈到达<canvas>上边界时,它们开始闪烁,有时会更改颜色。 Here's the JSFIDDLE . 这是JSFIDDLE What am i doing wrong? 我究竟做错了什么? Thanks. 谢谢。

for...in is great for iterating over objects, but it's not designed for iterating over arrays. for...in非常适合遍历对象,但并非旨在遍历数组。 In essence, your i is jumping around a bit. 从本质上讲,您的i有点跳。 Instead of using for...in , use this (very efficient) loop: 而不是使用for...in ,而是使用以下(非常有效的)循环:

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. 分叉的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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