简体   繁体   中英

How do you force a canvas refresh in Javascript

In the code that follows the function board repaints the canvas. However the canvas is not repainted until control reverts to the user. What code sequence is required to force a refresh whenever the function is invoked?

function doRound (ctx, game, loc, move){ // move is selected human move
    let go = move;
    let translate = {0:-1,1:-8,2:1,3:8}
    for (var i = 0; i < 2; i++) {
        loc = loc+translate[go]; // calculate move
        if (illegal(loc)){
            let text = (i === 0) ? "You lose!" : "You win!";
            document.getElementById("result").innerHTML = text;
            break;  // game over
        }       
        game[loc] = true; // place move on board
        board(ctx);  // refresh canvas
        if (i === 0){go = compMove()};  // calc computer move
    }
}

You would need to wipe off your canvas before redrawing all its previous content.

you can do so by using clearRect() and pass it the size of the canvas :

ctx.clearRect(0, 0, canvas.width, canvas.height);

here is a basic example on how this can be useful

 //note in javascript if an html element has an id a variable with the same name exists you can ommit to get it with document.getElementById("mycan"); let ctx=mycan.getContext("2d"); //initial rect position in x let move = 20; //does some heavy processing for no reason const heavyProcessing = (arr)=>{ for(let i = 0;i<1000000;i++) {arr.push(Math.floor(Math.random()*100)+1)} }; //adding an eventListener who listens to user input window.addEventListener("keydown",(e)=>{ //if(e.key=="ArrowRight){move++} increments x position of red square if the user presses the right arrow on his keyboard move+=(e.key=="ArrowRight"); }); //call to heavyProcessing before animation begins let ar=[]; heavyProcessing(ar); //simple animation timer setInterval(()=>{ //wipe off canvas before each redraw ctx.clearRect(0,0,mycan.width,mycan.height); //choose next rectangle color before drawing ctx.fillStyle = "red"; //drawing a rectangle ctx.fillRect(move,20,50,50); //recalls the code above every frame at a rate of 60 per second },1000/60)
 <canvas id = "mycan" width=300 height=200> </canvas>

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