0

我正在使用 Javascript 为 HTML5 Canvas 动画编写代码。我正在使用requestAnimFrame它。动画效果很好。requestAnimFrame但是当我在使用or的函数中添加一个循环(for 或 while)时setTimeout,动画不起作用。添加循环对我来说很重要。任何建议使这成为可能?

function animate(lastTime) {
            var date = new Date();
            var time = date.getTime();
            var timeDiff = time - lastTime;
            var linearSpeed = 100;
            var linearDistEachFrame = linearSpeed * timeDiff / 1000;
            var currentX = LINE.x;              
            var currentY = LINE.y;
                var newY = currentY + linearDistEachFrame;
                var newX = currentX + linearDistEachFrame;
                context.beginPath();
                context.moveTo(LINE.x, LINE.y);
                lastTime = time;

                var Xindex=LINE.arrayX.indexOf(newX);

                //here am getting error..if i replace this with 'if' its working fine..and even if there is not a single LOC it doesnt work
                 while(Xindex!=-1) {
                                        //processes the loop
                 }

                context.lineTo(LINE.x, LINE.y);
                context.fillStyle = "red";
                context.fill();
                context.lineWidth = LINE.borderWidth;
                context.strokeStyle = "red";
                context.stroke();
            // request new frame

            requestAnimFrame(function() {
                animate(lastTime);
            });
        }
4

1 回答 1

2

尝试break在循环中添加一条语句,看看是否可以修复它。如果是,则说明条件已经满足,代码会永远卡在循环中,除非你跳出来,或者把Xindex改成-1。

您需要准确缩小代码失败的位置。一种方法是在代码的关键部分打印调试语句,这样您就可以确定它们已被执行,以及重要变量的值是什么。

例如,您可以使用console.log("test");写入 Chrome 的 JavaScript 控制台、Firebug 或类似内容。

对于一个工作动画程序的调试输出,您将面临的一个问题是输出的冗长。您可能只想在某些有趣的情况下登录,否则您将被淹没在溪流中。数据的。

于 2012-04-16T11:59:24.950 回答