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