javascript - 立即显示对 HTML5 Canvas 的更改

标签 javascript html canvas html5-canvas

我正在使用 HTML5 Canvas 制作这个壁纸生成器。 ( https://github.com/arnav-t/pursuit-wallpapers )
它使用追踪曲线生成图案。
我希望生成过程是动画的并且对用户可见。
这些线是在 for 循环上绘制的,但它们仅在循环结束时显示在末尾(可以在提供的链接中看到实际操作)。为什么会出现这种情况?

神奇的事情发生在 for 循环中,我像这样重复画线:

for (let i=0; i < comp; ++i) {
    ctx.beginPath();
    ctx.strokeStyle = // something          
    ctx.moveTo( // somewhere );
    ctx.lineTo( // somewhere ) ;    
    ctx.lineWidth = // something
    ctx.stroke();
    ctx.closePath();
}

我尝试通过 setTimeout() 在每个帧之间添加延迟,但这没有帮助。

最佳答案

Javascript 异步运行。 for循环首先执行,然后在循环执行结束时查找 i 值,即 comp,然后输出setTimeOut comp 次,每次循环迭代一次。您始终只能看到最后一次执行的结果。您可以尝试以下操作,而不是使用 for 循环和 setTimeOut:

var maxlimit = 0;

function redrawCanvas() {
    ctx.beginPath();
    ctx.strokeStyle = // something          
    ctx.moveTo( // somewhere );
    ctx.lineTo( // somewhere ) ;    
    ctx.lineWidth = // something
    ctx.stroke();
    ctx.closePath();
    if(maxlimit < comp) {
        maxlimit++;
        setTimeout(redrawCanvas, 100);
    }
}

请告诉我这是否有帮助!

关于javascript - 立即显示对 HTML5 Canvas 的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769311/

相关文章:

javascript - 检查变量的类型

javascript - 当我只能通过引用复制另一个方法时,为什么还要使用 bind() 呢?

javascript - 正确的异步请求处理 - JS

javascript - Fabric.js - 多用户 Canvas

javascript - 如何使用 &lt;input type ="number"> 更改线宽?

javascript - 使 session 值可用于 JavaScript 的好方法是什么?

html - Ionic - 固定 div 在 ion-content 内滚动

html - div 不显示在文本框上方

jquery - 需要覆盖 CSS 背景色

jquery - 在 Canvas 顶部制作交互式文本区域