画布中的setTimeout

setTimeout in canvas

本文关键字:setTimeout 布中      更新时间:2023-09-26

这里有一个示例代码:

<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);

有人能告诉我有什么问题吗

试试这个:

Fiddle演示

HTML:

<canvas width="500" height="500"></canvas>

JavaScript:

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);
}