![](/img/trans.png)
[英]Proper way to perform update/draw loops on a canvas with requestAnimationFrame
[英]Is this the proper way to use requestAnimationFrame?
我有一個我編寫的軟件,它會在更新邏輯完成后立即觸發屏幕重繪。 問題是更新邏輯每秒發生超過 1000 次。 瀏覽器無法如此快速地更新屏幕,因此我認為 requestAnimationFrame 將允許我以較慢的方式為用戶更新屏幕。
我這樣構造代碼:
function repaint(){
now = Date.now();
elapsed = now-then;
if(elapsed > 2000){
.
.
.
//animation goes here
.
.
.
then = Date.now();
}
}
function startRepaint(){
then = Date.now();
requestAnimationFrame(repaint);
}
while(count < 1000){
.
.
.
startRepaint();
.
.
.
}
我可以以這種方式使用 requestAnimationFrame 來實現我想要的功能嗎?
你在這里擁有的不是你想要的。
每次執行 while 循環時,都會調用startRepaint()
,它會發出對動畫幀的請求。
第一次調用該函數后,您將遍歷 while 循環並再次調用它。 當您第二次調用此函數時,您可能還沒有收到第一個動畫幀。
理想情況下,您希望對其進行設置,以便調用更新函數,該函數又會發送下一個請求。
function repaint() {
...
requestAnimationFrame(repaint);
}
這樣做可以確保您在嘗試開始下一個之前始終完成完整的代碼框架。
您可以在重繪函數中使用計數器變量來跟蹤迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.