简体   繁体   English

为什么画布操作会滞后?

[英]Why do canvas operations lag?

Suppose I have the following code in javascript, which interacts with a HTML canvas: 假设我在javascript中具有以下代码,该代码与HTML画布进行交互:

function draw(){
    canvas.width = canvas.width
    canvas.style.backgroundColor = 'red'
    alert('drawn')
}

function wait(){
    alert('waiting')
    while (true){
    }
}

function call(){
    draw()
    wait()
}

and then I call the function call() . 然后我调用函数call() What I'd expect to happen is that the function should call draw() , turning the canvas red, and then calling wait() and stalling. 我希望发生的是该函数应调用draw() ,将画布变红,然后调用wait()并停止。 And indeed, the window alerts "drawn" and "waiting" as expected. 实际上,该窗口会按预期警告“已绘制”和“正在等待”。 However, the canvas doesn't turn red until the function wait() ends. 但是,直到函数wait()结束,画布才会变为红色。 (which, in this case will never happen). (在这种情况下将永远不会发生)。 Why does the canvas lag like this, and, supposing that my wait() function were instead some function that takes a few seconds to execute, how can I get the canvas to fully update in the draw() function before going on to the wait() function? 为什么画布会像这样滞后,并且假设我的wait()函数是一些需要花费几秒钟执行的函数,在继续wait()之前,如何在draw()函数中使画布完全更新? wait()功能?

The function wait will never exit. 功能wait永远不会退出。

function wait(){  
    while (true){  // infinite loop will never exit
    }
}

Maybe you want something like. 也许您想要类似的东西。

setTimeout(waitFunction,0); // call the waitFunction in 0ms

This will make the red canvas appear because you you have exited the current execution allowing for the canvas back buffer to be display. 这将使红色的画布出现,因为您已经退出了当前执行,从而可以显示画布后退缓冲区。 This only happens when there is no javascript running. 仅当没有运行JavaScript时才会发生这种情况。 Even if it is just 0ms it still tells the browser you have finished painting to a DOM element and you would like the results seen. 即使只有0ms,它仍然告诉浏览器您已经完成了对DOM元素的绘制,并且您希望看到结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM