这是我的一个示例代码:
<canvas width="500" height="500"></canvas>
<script>
var cx = document.querySelector("canvas").getContext("2d");
cx.beginPath();
for (var y = 0; y < 500; y+=10) {
cx.moveTo(0,0);
cx.lineTo(500,y);
}
cx.lineWidth = 3;
cx.strokeStyle = 'blue';
cx.stroke();
</script>
从一个点开始创建50行。我想为每一行使用setTimeout
。所以我认为下面的代码应该完成工作,但它不起作用:
setTimeout(function() {
for (var y = 0; y < 500; y+=10) {
cx.moveTo(0,0);
cx.lineTo(500,y);
cx.stroke();
}
}, 300);
有人可以告诉我这是什么问题
答案 0 :(得分:1)
试试这个:
<canvas width="500" height="500"></canvas>
var start = 0;
var leftX = start;
var leftY = start;
var end = 500;
var cx = document.querySelector("canvas").getContext("2d");
cx.beginPath();
cx.lineWidth = 3;
cx.strokeStyle = 'blue';
for (y = start; y < end; y++) {
window.setTimeout(function () {
cx.moveTo(start, start);
cx.lineTo(leftX, leftY);
cx.stroke();
leftX++;
leftY++;
}, 1 + (y * 20) / 3);
}