2025年4月16日 星期三

在網頁作動畫現在有更好的選擇requestAnimationFrame

網頁作動畫應該很直覺都是使用setTimeout()或setInterval(),但timer其實不是這麼精準的

但記載前幾天叫grok幫我寫程式時他給了我一個方法

requestAnimationFrame()

激起我的興趣我去查了一下

出自網站

https://ithelp.ithome.com.tw/m/articles/10186735

我直接附上裡面的程式碼,有時間再研究囉,據說可以依照機器的好壞把時間控制在微秒,然後這竟然還是八年前就有的東西我的天啊


function startAnimation() {
var start = null;
var limit = 2000;
var count = 0;
requestAnimationFrame(animation);
function animation(t) {
count++;
if(start === null) start = t;
if(t-start < limit) {
console.log(t, start, count);
requestAnimationFrame(animation);
} else {
console.log('done.');
}
}
}

沒有留言:

張貼留言