我已经研究了很多,主要是在 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>