简体   繁体   中英

Why do canvas operations lag?

Suppose I have the following code in javascript, which interacts with a HTML canvas:

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() . What I'd expect to happen is that the function should call draw() , turning the canvas red, and then calling wait() and stalling. And indeed, the window alerts "drawn" and "waiting" as expected. However, the canvas doesn't turn red until the function wait() ends. (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?

The function wait will never exit.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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