建议使用setTimeout从循环内重绘html画布的方法

hel*_*ker 2 html javascript animation canvas settimeout

我已经研究了很多,主要是在SO中,关于setTimeout"不阻塞",因此不适合在for循环中使用,因为循环继续进行,而一个函数调用不断积累.

我有一个记录图像处理算法的HTML文件,因此我希望以"人类可读"的速度显示活动像素"行走".我尝试过但不起作用的实现如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>

<body onload="run();">

    <canvas id="Canvas" width=501 height=601></canvas>

    <script>

        function run() {
            reevaluate();
        };

        var fixedcenteri;
        var fixedcenterj;



        function reevaluate() {

            var altura_imagem = 50;
            var largura_imagem = 40;

            for (var i = 0; i < altura_imagem; i++) {
                for (var j = 0; j < largura_imagem; j++) {

                    fixedcenteri = i;
                    fixedcenterj = j;

                    setTimeout(draw, 100);


                    // if I uncomment this I can see what I want, but...
                    // alert(i+j);
                };
            };
        };


        function draw () {
            var elem = document.getElementById('Canvas');
            var cx = elem.getContext('2d');

            w = elem.width;
            h = elem.height;

            cx.fillStyle = "white";
            cx.fillRect(0,0,w,h);

            cx.fillStyle = 'blue';
            cx.fillRect(fixedcenteri, fixedcenterj, 10, 10);
        }

    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

mar*_*rkE 5

试试RequestAnimationFrame!

RequestAnimationFrame与setTimeout一样是异步的,它比setTimeout更有效.

此外,它还为离屏动画提供动画分组和自动停止功能.

您甚至可以使用此技术将其限制为所需的FPS:

var fps = 15;
function draw() {
    setTimeout(function() {
        requestAnimationFrame(draw);

        // your draw() stuff goes here

    }, 1000 / fps);
}
Run Code Online (Sandbox Code Playgroud)