javascript – 仅在循环结束后重绘Canvas
作者:互联网
我在循环中绘制画布时遇到问题.
我想要实现的是,在每个循环中,脚本等待几毫秒,然后在画布上绘制,用户实际上可以看到更改,然后循环重复.
它的作用是用户无法看到更改,直到for循环结束.
但我发现,如果我显示一个警告窗口并且脚本等待用户响应,它实际上会绘制更改.
如何在每个循环中显示“小变化”,而不仅仅是最终?
我的代码(也在这里:http://janiczek.github.com/heighway-dragon/链接现在包含其他内容):
<script type="text/javascript">
function sleep (ms)
{
var start = new Date().getTime();
while (new Date().getTime() < start + ms)
continue;
};
function draw (withalert)
{
if (withalert == null) withalert = false;
var cur_x = 100 - .5;
var cur_y = 200 - .5;
length = 3;
steps = 20;
c.strokeStyle = "#f00";
canvas.width = canvas.width;
for (var count = 0; count < steps; count++)
{
sleep(100);
c.beginPath();
c.moveTo(cur_x, cur_y);
cur_x += length;
c.lineTo(cur_x, cur_y);
c.stroke();
if (withalert) alert(count);
}
};
</script>
<canvas id=canvas width=300 height=300 style="border: 2px solid #000"></canvas><br>
<input type="submit" value="Without alert" onclick="draw()">
<input type="submit" value="With alert" onclick="draw(true)">
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
</script>
解决方法:
使用setTimeout而不是sleep函数来临时释放UI线程.请注意,setTimeout设置最小延迟,如果在调度函数调度之前执行的某些操作所花费的时间超过传递给setTimeout的延迟,则传入其中的函数可能会延迟更长时间.
例如.用以下内容替换你的for循环:
var count = 0;
var drawPortion = function() {
c.beginPath();
c.moveTo(cur_x, cur_y);
cur_x += length;
c.lineTo(cur_x, cur_y);
c.stroke();
count++;
if(count < steps) { setTimeout(drawPortion, 100); }
};
drawPortion();
标签:javascript,loops,canvas,redraw 来源: https://codeday.me/bug/20190626/1297808.html