[英]By using HTML5 canvas, how to create infinite loop with time interval
我想用HTML5畫布不斷更新我的圖像位置。 我嘗試了以下javascript代碼來完成這項工作
window.onload = function start() {
update();
}
function update() {
document.getElementById('scoreband').innerHTML = score;
var style = document.getElementById('bug').style;
timmer = window.setInterval(function () {
style.left = ((Math.random() * 100) + 1) + "%";
style.top = ((Math.random() * 100) + 19) + "%";
}, num);
}
但是當談到HTML5畫布時,這不起作用。 是否有類似的方法在HTML5畫布中執行相同的工作?
要更改任何可視DOM內容,您應該使用requestAmimationFrame
例如
function update(time){
// time is in ms and has a 1/1000000 second accuracy
// code that changes some content, like the canvas
requestAnimationFrame(update); // requests the next frame in 1/60th second
}
並開始它
requestAnimationFrame(update);
按照要求
indow.onload = function start() {
requestAnimationFrame(update);
}
function update() {
document.getElementById('scoreband').innerHTML = score;
var style = document.getElementById('bug').style;
style.left = ((Math.random() * 100) + 1) + "%";
style.top = ((Math.random() * 100) + 19) + "%";
requestAnimationFrame(update);
}
雖然它不如requestAnimationFrame好,但setInterval的幀速率可以是動態的。
//supposing num is defined lol
var timer = setInterval(update, num);
function update() {
document.getElementById('scoreband').innerHTML = score;
var style = document.getElementById('bug').style;
style.left = ((Math.random() * 100) + 1) + "%";
style.top = ((Math.random() * 100) + 19) + "%";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.