首页 > 解决方案 > 你如何在Javascript中强制画布刷新

问题描述

在功能板后面的代码中,重新绘制了画布。然而,直到控制权归还给用户,画布才会重新绘制。每当调用该函数时,需要什么代码序列来强制刷新?

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

标签: javascriptanimationcanvasrefresh

解决方案


在重绘所有以前的内容之前,您需要擦掉画布。

您可以通过使用 clearRect() 来做到这一点并将其传递给画布的大小:

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

这是一个关于这如何有用的基本示例

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


推荐阅读