[英]How to loop canvas animation?
我試圖理解動畫。 當我需要創建循環時,我似乎總是被卡住。 所以,我有兩個不同的 styles,我希望它們每隔幾秒或 1 秒交換一次,沒關系。
document.getElementById("square").style.backgroundColor = "red"; document.getElementById("square").style.border = "2px solid black"; const c = document.getElementById("square"); const ctx = c.getContext("2d"); const repaint = () => { document.getElementById("square").style.backgroundColor = "white"; ctx.fillStyle = "red"; ctx.fillRect(0, 0, 200, 200); ctx.fillRect(400, 0, 200, 200); ctx.fillRect(200, 200, 200, 200); ctx.fillRect(600, 200, 200, 200); }; const draw = () => { if (c.getContext) { ctx.beginPath(); ctx.moveTo(0, 200); ctx.lineTo(800, 200); ctx.moveTo(400, 0); ctx.lineTo(400, 400); ctx.moveTo(200, 0); ctx.lineTo(200, 400); ctx.moveTo(600, 0); ctx.lineTo(600, 400); ctx.stroke(); ctx.fillStyle = "white"; ctx.fillRect(0, 0, 200, 200); ctx.fillRect(400, 0, 200, 200); ctx.fillRect(200, 200, 200, 200); ctx.fillRect(600, 200, 200, 200); } else { // canvas-unsupported code here } }; window.requestAnimationFrame(draw); setInterval(repaint, 1000);
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Animated flag</title> </head> <body> <div> </div> <canvas id="square" width="800" height="400"></canvas> <script src="./red-white-animation.js"></script> </body> </html>
在此示例中,我想要實現的目標只發生一次。 紅色方塊變為白色,白色變為紅色。 如何實現這種行為不斷發生?
我有這兩個功能,我的想法是每隔幾秒鍾在它們之間切換一次,但就我閱讀的有關 canvas 和動畫的內容而言,我無法全神貫注於此以及如何做到這一點。
首先,您每 1000 毫秒使用 setInterval 調用的 function 繪制相同的模式。 你調用一次 requestAnimationFrame,它會在事件循環的渲染階段應用一次,傳遞給 requestAnimationFrame 的 function 將永遠不會被再次調用。 相反,您使用 setInterval 重復應用 repaint 中的代碼。 如果你想重繪每次都繪制不同的圖案,你應該跟蹤一個全局變量 state,它指示下一個要繪制的圖案
let drawState = 0
const repaint = () => {
if (drawState) {
// clear and redraw the first pattern
}
else {
// clear and redraw the second pattern
}
drawState ^= 1;
}
但是你的代碼還有一個更大的問題。 setInterval 是一種已棄用的 JS 動畫方式。 這是因為傳遞給 setInterval 的 function 是在事件循環的不同部分執行的,而不是渲染部分。 requestAnimationFrame 正是出於這個原因而創建的——它在每一幀呈現頁面內容之前附加傳遞給它的 function。 所以你的代碼應該只使用 requestAnimationFrame 並且看起來像這樣
function animate() {
// call functions for drawing the frame
...
// Prepare the animation code execution for the next frame
requestAnimationFrame(animate);
}
animate();
知道每 1000 毫秒執行 60 幀,您可以通過每 60 次調用 animate() 更改模式來實現計時。
我建議您閱讀更多關於 JS 事件循環和 requestAnimationFrame 的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.