HTML5-2【requestAnimationFrame、迴圈字母】
阿新 • • 發佈:2021-02-15
技術標籤:HTML5javascriptjshtmlhtml5
一.requestAnimationFrame
(1).基礎內容
(2).使用方法
function animate(){
requestAnimationFrame(animate)
}
animate()
FPS全稱呼(Frames per second)每秒重新整理次數
會一直保持在60fps,小於60則是動畫過於複雜或動畫執行時瀏覽器的頁面上還有很多其他的事還在發生
(3).相容性
var requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame||
window.webkitRequestAnimationFrame||
window.msRequestAnimationFrame;
二.迴圈字母
(1).控制幀率
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="container"> <h1 id="letter">a</h1> </div> <script> let letter = document.getElementById('letter'), framesPerSecond = 10; let letters = 'abcdefghijklmnopqrstuvwxyz'.split(''); function cycleLetter(){ setTimeout(()=>{ requestAnimationFrame(cycleLetter); let curLetter,idx; idx = Math.floor(Math.random() * letters.length); curLetter = letters[idx]; letter.innerHTML = curLetter; },1000/framesPerSecond) } cycleLetter() </script> </body> </html>
(2).停止動畫
<script> let letter = document.getElementById('letter'), framesPerSecond = 10, running = false; let letters = 'abcdefghijklmnopqrstuvwxyz'.split(''); function cycleLetter(){ setTimeout(()=>{ requestAnimationFrame(cycleLetter); if(running){ let curLetter,idx; idx = Math.floor(Math.random() * letters.length); curLetter = letters[idx]; letter.innerHTML = curLetter; } },1000/framesPerSecond) } cycleLetter() </script>
通過requestId停止,用來儲存requestAnimationFrame的ID的一個變數
cancelAnimationFrame(requestId)來終止
requestAnimationFrame預設會有id數字的返回值
<div id="container">
<h1 id="letter">a</h1>
</div>
<script>
let letter = document.getElementById('letter'),
framesPerSecond = 10,
bodyElem = document.getElementsByTagName('body')[0],
requestID;
bodyElem.addEventListener('click',stopAnimation,false);
let letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
function cycleLetter(){
let curLetter,idx;
idx = Math.floor(Math.random() * letters.length);
curLetter = letters[idx];
letter.innerHTML = curLetter;
requestID = requestAnimationFrame(cycleLetter);
}
cycleLetter()
function stopAnimation(){
cancelAnimationFrame(requestID)
}
</script>