window.requestAnimationFrame()
method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
requestAnimationFrame()
if you want to animate another frame at the next repaint.
You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.
requestAnimationFrame()
calls are paused in most browsers when running in background tabs or hidden
<iframe>
s in order to improve performance and battery life.
The callback method is passed a single argument, a
DOMHighResTimeStamp
, which indicates the current time (based on the number of milliseconds since
time origin
). When callbacks queued by
requestAnimationFrame()
begin to fire multiple callbacks in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. This timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 µs).
Be sure to always use the first argument (or some other method for getting the current time) to calculate how much the animation will progress in a frame, otherwise the animation will run faster on high refresh rate screens . Check the example below for a way to do this.
window.requestAnimationFrame(callback);
callback
DOMHighResTimeStamp
similar to the one returned by
performance.now()
, indicating the point in time when
requestAnimationFrame()
starts to execute callback functions.
A
long
integer value, the request id, that uniquely identifies the entry in the callback list. This is a non-zero value, but you may not make any other assumptions about its value. You can pass this value to
window.cancelAnimationFrame()
to cancel the refresh callback request.
In this example, an element is animated for 2 seconds (2000 milliseconds). The element moves at a speed of 0.1px/ms to the right, so its relative position (in CSS pixels) can be calculated in function of the time elapsed since the start of the animation (in milliseconds) with
0.1 * elapsed
. The element's final position is 200px (
0.1 * 2000
) to the right of its initial position.
const element = document.getElementById('some-element-you-want-to-animate');
let start;
function step(timestamp) {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start;
// `Math.min()` is used here to make sure that the element stops at exactly 200px.
element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';
if (elapsed < 2000) { // Stop the animation after 2 seconds
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
Edge versions below 17 and Internet Explorer do not reliably fire
requestAnimationFrame
before the paint cycle.
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'requestAnimationFrame' in that specification. |
实时标准 | No change, supersedes the previous one. |
|
Timing control for script-based animations
The definition of 'requestAnimationFrame' in that specification. |
过时 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
requestAnimationFrame
|
Chrome
24
|
Edge 12 |
Firefox
23
注意事项
|
IE 10 |
Opera
15
|
Safari
6.1
|
WebView Android
≤37
|
Chrome Android
25
|
Firefox Android
23
|
Opera Android
14
|
Safari iOS
7
|
Samsung Internet Android
1.5
|
| 返回值 | Chrome 23 | Edge 12 | Firefox 11 | IE 10 | Opera 15 | Safari 6.1 | WebView Android Yes | Chrome Android 25 | Firefox Android 14 | Opera Android 14 | Safari iOS 6.1 | Samsung Internet Android 1.5 |
完整支持
见实现注意事项。
要求使用供应商前缀或不同名称。
Window.mozAnimationStartTime
Window.cancelAnimationFrame()
Window
applicationCache
caches
closed
console
controllers
crossOriginIsolated
crypto
customElements
defaultStatus
devicePixelRatio
dialogArguments
目录
document
event
frameElement
frames
fullScreen
history
indexedDB
innerHeight
innerWidth
isSecureContext
isSecureContext
length
localStorage
location
locationbar
menubar
mozAnimationStartTime
mozInnerScreenX
mozInnerScreenY
mozPaintCount
名称
navigator
onabort
onafterprint
onanimationcancel
onanimationend
onanimationiteration
onappinstalled
onauxclick
onbeforeinstallprompt
onbeforeprint
onbeforeunload
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondevicelight
ondevicemotion
ondeviceorientation
ondeviceorientationabsolute
ondeviceproximity
ondragdrop
ondurationchange
onended
onerror
onfocus
onformdata
ongamepadconnected
ongamepaddisconnected
ongotpointercapture
onhashchange
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onlanguagechange
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmessage
onmessageerror
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmozbeforepaint
onpaint
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onpopstate
onrejectionhandled
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onstorage
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onunhandledrejection
onunload
onuserproximity
onvrdisplayactivate
onvrdisplayblur
onvrdisplayconnect
onvrdisplaydeactivate
onvrdisplaydisconnect
onvrdisplayfocus
onvrdisplaypointerrestricted
onvrdisplaypointerunrestricted
onvrdisplaypresentchange
onwheel
opener
origin
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
性能
personalbar
pkcs11
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sessionStorage
sidebar
speechSynthesis
status
statusbar
toolbar
top
visualViewport
window
alert()
atob()
back()
blur()
btoa()
cancelAnimationFrame()
cancelIdleCallback()
captureEvents()
clearImmediate()
clearInterval()
clearTimeout()
close()
confirm()
convertPointFromNodeToPage()
convertPointFromPageToNode
createImageBitmap()
dump()
fetch()
find()
focus()
forward()
getAttention()
getComputedStyle()
getDefaultComputedStyle()
getSelection()
home()
matchMedia()
minimize()
moveBy()
moveTo()
open()
openDialog()
postMessage()
print()
prompt()
queueMicrotask()
releaseEvents()
requestAnimationFrame()
requestFileSystem()
requestIdleCallback()
resizeBy()
resizeTo()
restore()
routeEvent()
scroll()
scrollBy()
scrollByLines()
scrollByPages()
scrollTo()
setCursor()
setImmediate()
setInterval()
setTimeout()
showModalDialog()
sizeToContent()
stop()
updateCommands()
event
afterprint
animationcancel
animationend
animationiteration
beforeprint
beforeunload
blur
copy
cut
DOMContentLoaded
error
focus
hashchange
languagechange
load
message
messageerror
offline
online
orientationchange
pagehide
pageshow
paste
popstate
rejectionhandled
storage
transitioncancel
unhandledrejection
unload
vrdisplayconnect
vrdisplaydisconnect
vrdisplaypresentchange