javascript - 你如何在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
}
}
解决方案
在重绘所有以前的内容之前,您需要擦掉画布。
您可以通过使用 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>
推荐阅读
- c++ - 以排序方式在单循环链表中插入元素
- javascript - Edge中XML解析后如何保持属性的顺序?
- java -
spring boot mysql插入问题 - python-3.x - 无法让分页爬虫工作 Python3
- python - 如果未在 Setupui 中启动,如何在菜单命令中显示 tablewidget
- c# - Xamarin.Android:如何将 WebView 登录凭据传递到 HttpWebRequest?
- python-asyncio - 异步任务与协程
- python - 推送到 Heroku 更改未修改文件的修改日期
- powershell - 在 PowerShell 中,我必须将 AzureStack Powershell 模块版本值存储为变量
- python - authlib 中的 Mongodb 支持