一.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>