requestAnimationFrame会在浏览器下一次重绘前调用,接收一个callback回调函数作为参数,常常用来处理一些动画效果。requestAnimationFrame会返回一个a long integer value,可以用cancelAnimationFrame方法传入这个数来取消调用。
- MDN上面的例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#some-element-you-want-to-animate {
background: #ff0;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div id="some-element-you-want-to-animate"></div>
<script>
const element = document.getElementById('some-element-you-want-to-animate')
let start
let previousTimeStamp
let done = false
//timestamp:开始执行回调函数的时间点,与performance.now()的值类似
function step(timestamp) {
if (start === undefined) {
start = timestamp
}
const elapsed = timestamp - start
if (previousTimeStamp !== timestamp) {
// Math.min() is used here to make sure the element stops at exactly 200px
const count = Math.min(0.1 * elapsed, 200)
element.style.transform = 'translateX(' + count + 'px)'
if (count === 200) done = true
}
if (elapsed < 2000) { // Stop the animation after 2 seconds
previousTimeStamp = timestamp
!done && window.requestAnimationFrame(step)
}
}
window.requestAnimationFrame(step)
</script>
</body>
</html>
- 使用cancelAnimationFrame取消
const element = document.getElementById('some-element-you-want-to-animate')
let start
let previousTimeStamp
let requestId
//timestamp:开始执行回调函数的时间点,与performance.now()的值类似
function step(timestamp) {
if (start === undefined) {
start = timestamp
}
const elapsed = timestamp - start
const count = Math.min(0.1 * elapsed, 200)
element.style.transform = 'translateX(' + count + 'px)'
if (elapsed < 2000) {
//每次执行时更新requestId
requestId = window.requestAnimationFrame(step)
}
if (elapsed > 1000) {
window.cancelAnimationFrame(requestId)
}
}
requestId = window.requestAnimationFrame(step)
- 兼容写法
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame
var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame