window.requestAnimationFrame使用

requestAnimationFrame会在浏览器下一次重绘前调用,接收一个callback回调函数作为参数,常常用来处理一些动画效果。requestAnimationFrame会返回一个a long integer value,可以用cancelAnimationFrame方法传入这个数来取消调用。

  • MDN上面的例子


  
    
    
    
  
  
    
  • 使用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

你可能感兴趣的:(window.requestAnimationFrame使用)