Search completed in 2.29 seconds.
104 results for "requestAnimationFrame":
Your results are loading. Please wait...
Window.requestAnimationFrame() - Web APIs
the 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.
... note: your callback routine must itself call requestanimationframe() if you want to animate another frame at the next repaint.
...requestanimationframe() calls are paused in most browsers when running in background tabs or hidden <iframe>s in order to improve performance and battery life.
...And 6 more matches
XRSession.requestAnimationFrame() - Web APIs
the xrsession method requestanimationframe(), much like the window method of the same name, schedules a callback to be executed the next time the browser is ready to paint the session's virtual environment to the xr display.
... the specified callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must call requestanimationframe() again.
... note: despite the obvious similarities between these methods and the global requestanimationframe() function provided by the window interface, you must not treat these as interchangeable.
...And 6 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
requestanimationframe() the modern version of setinterval().
... requestanimationframe() requestanimationframe() is a specialized looping function created for running animations efficiently in the browser.
... (read more about this on creativejs.) note: you can find examples of using requestanimationframe() elsewhere in the course — see for example drawing graphics, and object building practice.
...And 22 more matches
Anatomy of a video game - Game development
on the web, window.requestanimationframe() will be the foundation of most well-programmed per-frame main loops.
...here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents.
...calling the next requestanimationframe early ensures the browser receives it on time to plan accordingly even if your current frame misses its vsync window.
...And 20 more matches
Efficient animation for web games - Game development
we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe.
... use requestanimationframe when you are animating <canvas> content, or when your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout.
...requestanimationframe causes the browser to redraw and call your function before that frame gets to the screen.
...And 10 more matches
Rendering and the WebXR frame animation callback - Web APIs
this is done by calling the xrsession method requestanimationframe().
... kicking off the renderer thus looks like this: let worldrefspace; async function runxr(xrsession) { worldrefspace = await xrsession.requestreferencespace("immersive-vr"); if (worldrefspace) { viewerrefspace = worldrefspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsession.requestanimationframe(mydrawframe); } } after getting a reference space for the immersive world, this creates an offset reference space representing the position and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace().
... then the first animation frame is scheduled by calling the xrsession method requestanimationframe(), providing a callback function, mydrawframe(), whose job is to render the frame.
...And 7 more matches
Drawing graphics - Learn web development
there are a few javascript functions that will allow you to run functions repeatedly, several times a second, the best one for our purposes here being window.requestanimationframe().
...if that function draws the new update to your animation, then calls requestanimationframe() again just before the end of the function, the animation loop will continue to run.
... the loop ends when you stop calling requestanimationframe() or if you call window.cancelanimationframe() after calling requestanimationframe() but before the frame is called.
...And 6 more matches
Basic animations - Web APIs
scheduled updates first there's the window.setinterval(), window.settimeout(), and window.requestanimationframe() functions, which can be used to call a specific function over a set period of time.
... requestanimationframe(callback) tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
... in the examples below, we'll use the window.requestanimationframe() method to control the animation.
...And 6 more matches
CSS and JavaScript animation performance - Web Performance
there are many ways to implement web animations, such as css transitions/animations or javascript-based animations (using requestanimationframe()).
... requestanimationframe the requestanimationframe() api provides an efficient way to make animations in javascript.
...compared to settimeout()/setinterval(), which need a specific delay parameter, requestanimationframe() is much more efficient.
...And 6 more matches
Intensive JavaScript - Firefox Developer Tools
the first is to split long-running functions into pieces and use requestanimationframe to schedule each piece, and the second is to run the whole function in a separate thread using a web worker.
... there's also a video version of this walkthrough: the demo website looks like this: it has three controls: a radio button group to control how to run the javascript: as a single blocking operation in the main thread, as a series of smaller operations in the main thread using requestanimationframe(), or in another thread using a worker.
... using requestanimationframe in the first attempt at fixing this, we'll split up the function into a number of much smaller self-contained functions, and schedule each one using requestanimationframe().
...And 5 more matches
Using the Gamepad API - Web APIs
performing such checks tends to involve using the gamepad object in conjunction with an animation loop (e.g., requestanimationframe), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads.
... to start with, we declare some variables: the gamepadinfo paragraph that the connection info is written into, the ball that we want to move, the start variable that acts as the id for requestanimation frame, the a and b variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the requestanimationframe() and cancelanimationframe() cross browser forks.
...if so, we stop the requestanimationframe() loop (see below) and revert the gamepad information back to what it was originally.
...And 5 more matches
Performance best practices for Firefox front-end engineers
note that requestanimationframe() lets you queue up javascript to run right before the style flush occurs.
... this also means that requestanimationframe() is not a good place to put queries for layout or style information.
... return elem.clientwidth; }); requestanimationframe(() => { otherelem.style.width = `${width}px`; }); } please see the section on promisedocumentflushed in detecting and avoiding synchronous style flushes for more information on how to use the api.
...And 4 more matches
Index - Web APIs
WebAPIIndex
this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code.
... 4985 window.requestanimationframe() api, animations, dom, dom reference, drawing, games, graphics, intermediate, javascript timers, method, performance, reference, scheduling, window, requestanimationframe the window.requestanimationframe() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
... 5072 window.cancelanimationframe() api, animation, dom, experimental, method, reference, window the window.cancelanimationframe() method cancels an animation frame request previously scheduled through a call to window.requestanimationframe().
...And 4 more matches
Choosing the right approach - Learn web development
not as efficient as requestanimationframe(), but allows you to choose a running rate/frame rate.
...unless you need to choose a specific (slower) framerate, it is generally better to use requestanimationframe().
... further information cooperative asynchronous javascript: timeouts and intervals, in particular setinterval() setinterval() reference requestanimationframe() requestanimationframe() is a method that allows you to run a function repeatedly, and efficiently, at the best framerate available given the current browser/system.
...And 3 more matches
Background Tasks API - Web APIs
if your callback needs to change the dom, it should use window.requestanimationframe() to schedule that.
...in addition, this example demonstrates how to schedule updates to the document content using requestanimationframe().
...instead, we'll use requestanimationframe() to ask the browser to call us when it's safe to update the display.
...And 3 more matches
Advanced animations - Web APIs
again, window.requestanimationframe() helps us to control the animation.
...ll = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); boundaries without any boundary collision testing our ball runs out of the canvas quickly.
...; ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); acceleration to make the motion more real, you can play with the velocity like this, for example: ball.vy *= .99; ball.vy += .25; this slows down the vertical velocity each frame...
...And 3 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
; } else { refspacetype = "viewer"; } mat4.fromtranslation(cubematrix, viewerstartposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); return xrsession; } after storing the newly-created xrsession object into xrsession, the label of the button is set to "exit webxr" to indicate its new function after starting the scene, and a handler is installed for the end event, so we get notified when the xrsession ends.
...then we let the session know we're ready to draw a frame by calling its requestanimationframe() function.
... drawing a frame our callback for xrsession.requestanimationframe() is implemented in the drawframe() function shown below.
...And 2 more matches
Building up a basic demo with Three.js - Game development
our render() function will do this job, with a little help from requestanimationframe(), which causes the scene to be re-rendered constantly on every frame: function render() { requestanimationframe(render); renderer.render(scene, camera); } render(); on every new frame the render function is invoked, and the renderer renders the scene and the camera.
...add this line of code, right after the requestanimationframe() invocation inside the render function: cube.rotation.y += 0.01; this rotates the cube on every frame, by a tiny bit, so the animation looks smooth.
...add the following lines, just below the requestanimationframe() invocation: t += 0.01; torus.scale.y = math.abs(math.sin(t)); we use math.sin, ending up with quite an interesting result.
...add the following, again just below our requestanimationframe() invocation: dodecahedron.position.y = -7*math.sin(t*2); this will move the dodecahedron up and down, by applying the sin() value to the y axis on each frame, and a little adjustment to make it look cooler.
MozBeforePaint
whenever you're ready to refresh your animation, you call the window.requestanimationframe() method.
... the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions.
... <!doctype html> <html> <body> <div id="d" style="width:100px; height:100px; background:lime; position:relative;"></div> <script> var d = document.getelementbyid("d"); var start = window.mozanimationstarttime; function step(event) { var progress = event.timestamp - start; d.style.left = math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozrequestanimationframe(); } else { window.removeeventlistener("mozbeforepaint", step, false); } } window.addeventlistener("mozbeforepaint", step, false); window.mozrequestanimationframe(); </script> </body> </html> as you can see, each time the mozbeforepaint event fires, our step() method is called.
... this computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.requestanimationframe() to schedule the next animation frame to be drawn.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
this means that most frequently, you'll be using poses within your frame rendering code, which is executed as a callback from the xrframe method requestanimationframe().
... the only way to obtain a pose that adapts positional information from one space to another is through the xrframe object received by your frame rendering callback function specified when you called the xrsession method requestanimationframe().
... for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawframe); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawframe(currentframetime, frame) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefspace); animationframerequestid = session.requestanimationframe(mydrawframe); if (viewerpose) { /* ...
... let previousviewerpose = null; function mydrawframe(currentframetime, frame) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefspace); animationframerequestid = session.requestanimationframe(mydrawframe); if (viewerpose) { if (!previousviewerpose) { previousviewerpose = viewerpose; } let offsetmatrix = mat4.create(); mat4.sub(offsetmatrix, previousviewerpose.transform.matrix, viewerpose.transform.matrix); previousviewerpose = viewerpose; } } continuity and recovery after tracking loss sometimes, while the user is actively using their x...
window.cancelAnimationFrame() - Web APIs
the window.cancelanimationframe() method cancels an animation frame request previously scheduled through a call to window.requestanimationframe().
... syntax window.cancelanimationframe(requestid); parameters requestid the id value returned by the call to window.requestanimationframe() that requested the callback.
... examples var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.msrequestanimationframe; var cancelanimationframe = window.cancelanimationframe || window.mozcancelanimationframe; var start = window.mozanimationstarttime; // only supported in ff.
... var myreq; function step(timestamp) { var progress = timestamp - start; d.style.left = math.min(progress / 10, 200) + 'px'; if (progress < 2000) { // it's important to update the requestid each time you're calling requestanimationframe myreq = requestanimationframe(step); } } myreq = requestanimationframe(step); // the cancelation uses the last requestid cancelanimationframe(myreq); specifications specification status comment html living standardthe definition of 'cancelanimationframe()' in that specification.
Window.onmozbeforepaint - Web APIs
this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code.
... example see window.mozrequestanimationframe() for an example.
... notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozrequestanimationframe().
...this time is the same for all animations being run in the same browser window, including those using the window.mozrequestanimationframe() method, css transitions, and smil animations.
XRSession.cancelAnimationFrame() - Web APIs
the cancelanimationframe() method of the xrsession interface cancels an animation frame which was previously requested by calling requestanimationframe.
... syntax xrsession.cancelanimationframe(handle); parameters handle the unique value returned by the call to requestanimationframe() that previously scheduled the animation callback.
...once started, the session schedules its first frame to be rendered by calling requestanimationframe().
... const xr = navigator.xr; let requesthandle = null; let xrsession = null; if (xr) { xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { startxr(); } }); } function framecallback(time, xrframe) { xrsession.requestanimationframe(framecallback); // update and render the frame } async function startxr() { xrsession = xr.requestsession("immersive-vr"); if (xrsession) { stopbutton.onclick = stopxr; requesthandle = xrsession.requestanimationframe(framecallback); } } function pausexr() { if (xrsession && requesthandle) { xrsession.cancelanimationframe(requesthandle); requesthandle = null; } } ...
XRSession - Web APIs
WebAPIXRSession
cancelanimationframe() removes a callback from the animation frame painting callback from xrsession's set of animation frame rendering callbacks, given the identifying handle returned by a previous call to requestanimationframe().
... requestanimationframe() schedules the specified method to be called the next time the user agent is working on rendering an animation frame for the webxr device.
...this method is comparable to the window.requestanimationframe() method.
... const xr = navigator.xr; if (xr) { xr.requestsession("inline").then((xrsession) => { xrsession.requestreferencespace("local").then((xrreferencespace) => { xrsession.requestanimationframe((time, xrframe) => { let viewer = xrframe.getviewerpose(xrreferencespace); gl.bindframebuffer(xrwebgllayer.framebuffer); for (xrview of viewer.views) { let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); } }); }); }); } else { /* we...
JavaScript timers - Archive of obsolete content
but there are some javascript native functions (timers) which allow us to delay the execution of arbitrary instructions: settimeout() setinterval() setimmediate() requestanimationframe() the settimeout() function is commonly used if you wish to have your function called once after the specified delay.
...the requestanimationframe() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame.
... requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame.
Index - Game development
2 anatomy of a video game games, javascript, main loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game.
...we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe.
... 64 finishing up beginner, canvas, games, javascript, tutorial, lives, requestanimationframe there's always room for improvements in any game we write.
Finishing up - Game development
drawlives(); improving rendering with requestanimationframe() now let's work on something that is not connected to the game mechanics, but to the way it is being rendered.
... requestanimationframe helps the browser render the game better than the fixed framerate we currently have implemented using setinterval().
... replace the following line: var interval = setinterval(draw, 10); with simply: draw(); and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to call itself over and over again: requestanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser.
Index - Learn web development
49 asynchronous javascript beginner, codingscripting, guide, javascript, landing, promises, async, asynchronous, await, callbacks, requestanimationframe, setinterval, settimeout in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
... 50 choosing the right approach beginner, intervals, javascript, learn, optimize, promises, async, asynchronous, await, requestanimationframe, setinterval, settimeout, timeouts to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate.
... 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, codingscripting, guide, intervals, javascript, loops, asynchronous, requestanimationframe, setinterval, settimeout, timeouts this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g.
Object building practice - Learn web development
the finished example will look a little something like this: this example will make use of the canvas api for drawing the balls to the screen, and the requestanimationframe api for animating the whole display — you don't need to have any previous knowledge of these apis, and we hope that by the time you've finished this article you'll be interested in exploring them more.
... add the following to the bottom of your code now: function loop() { ctx.fillstyle = 'rgba(0, 0, 0, 0.25)'; ctx.fillrect(0, 0, width, height); for (let i = 0; i < balls.length; i++) { balls[i].draw(); balls[i].update(); } requestanimationframe(loop); } all programs that animate things generally involve an animation loop, which serves to update the information in the program and then render the resulting view on each frame of the animation; this is the basis for most games and other such programs.
... runs the function again using the requestanimationframe() method — when this method is repeatedly run and passed the same function name, it runs that function a set number of times per second to create a smooth animation.
Document: scroll event - Web APIs
instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows.
...this example optimizes thescroll event for requestanimationframe.
... // reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); see more, similar examples on the resize event page.
Element: scroll event - Web APIs
instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows.
...this example optimizes thescroll event for requestanimationframe.
... // reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); note: you can find more examples on the resize event page.
Visual Viewport API - Web APIs
one thing that may not be clear in this example is the use of the pendingupdate flag and the call to requestanimationframe().
...using requestanimationframe() ensures that the transform ocurrs before the next render.
... let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) return; pendingupdate = true; requestanimationframe(() => { pendingupdate = false; var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin.
A basic 2D WebGL animation example - Web APIs
entrotation); gl.uniform4fv(uglobalcolor, [0.1, 0.7, 0.2, 1.0]); gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enablevertexattribarray(avertexposition); gl.vertexattribpointer(avertexposition, vertexnumcomponents, gl.float, false, 0, 0); gl.drawarrays(gl.triangles, 0, vertexcount); window.requestanimationframe(function(currenttime) { let deltaangle = ((currenttime - previoustime) / 1000.0) * degreespersecond; currentangle = (currentangle + deltaangle) % 360; previoustime = currenttime; animatescene(); }); } the first thing that needs to be done in order to draw a frame of the animation is to clear the background to the desired color.
...that's done here by calling requestanimationframe(), which asks that a callback function be executed the next time the browser is ready to update the screen.
... our requestanimationframe() callback receives as input a single parameter, currenttime, which specifies the time at which the frame drawing began.
Using bounded reference spaces - Web APIs
xrsession.requestanimationframe(ondrawframe); } if you compare this code to the code used in examples using unbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor.
...from the above snippet to: function onrefspacecreated(refspace) { xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); let startposition = vec3.fromvalues(0, 1.5, 0); const startorientation = vec3.fromvalues(0, 0, 1.0); xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, startorientation)); xrsession.requestanimationframe(ondrawframe); } in this code, executed after the reference space has been created, we create an xrrigidtransform representing the transform that will move the viewpoint upward by 1.5 meters.
...finally, drawing begins by calling the xrsession method requestanimationframe().
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
here's what that looks like conceptually: your code tells the webxr engine that you want to provide the next animation frame by calling the xrsession method requestanimationframe(), providing a callback function that renders a frame of animation.
... example frame callback a fairly basic (but typical) callback for rendering frames might look like this: function myanimationframecallback(time, frame) { let adjustedrefspace = applypositionoffsets(xrreferencespace); let pose = frame.getviewerpose(adjustedrefspace); animationframerequestid = frame.session.requestanimationframe(myanimationframecallback); if (pose) { let gllayer = frame.session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); checkglerror("binding the framebuffer"); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); checkglerror("clearing the framebuffer"); const deltatime = (time - last...
... next, we go ahead and queue up the request to render the next frame of video, so we don't have to worry about doing it later, by simply calling requestanimationframe() again.
WebXR application life cycle - Web APIs
call the xrsession method requestanimationframe() to schedule the first frame render for the xr device.
... each requestanimationframe() callback should use the information provided about the objects located in the 3d world to render the frame using webgl.
... each time the callback is invoked, it should call requestanimationframe() again in order to let the browser know that the callback needs to be run again when it's time to render the next frame.
Starting up and shutting down a WebXR session - Web APIs
ate({ baselayer: new xrwebgllayer(worlddata.session, gl) }); // start rendering the scene referencespace = await worlddata.session.requestreferencespace("unbounded"); worlddata.referencespace = referencespace.getoffsetreferencespace( new xrrigidtransform(worlddata.playerspawnposition, worlddata.playerspawnorientation)); worlddata.animationframerequestid = worlddata.session.requestanimationframe(ondrawframe); return worlddata; } for the purposes of this example, an object named worlddata gets created to encapsulate data about the world and rendering environment.
... this includes the xrsession itself, all of the data used to render the scene in webgl, the world reference space, and the id returned by requestanimationframe().
... with the new reference space in hand and stored into the worlddata object for safe-keeping, we call the session's requestanimationframe() method to schedule a callback to be executed when it's time to render the next frame of animation for the webxr session.
Visualizations with Web Audio API - Web APIs
escribed in the previous section to set up the buffer: analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); next, we clear the canvas of what had been drawn on it before to get ready for the new visualization display: canvasctx.clearrect(0, 0, width, height); we now define the draw() function: function draw() { in here, we use requestanimationframe() to keep looping the drawing function once it has been started: var drawvisual = requestanimationframe(draw); next, we grab the time domain data and copy it into our array analyser.getbytetimedomaindata(dataarray); next, fill the canvas with a solid colour to start canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); set a line width and stroke colour for th...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); next, we start our draw() function off, again setting up a loop with requestanimationframe() so that the displayed data keeps updating, and clearing the display with each animation frame.
... function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); now we set our barwidth to be equal to the canvas width divided by the number of bars (the buffer length).
Window - Web APIs
WebAPIWindow
window.cancelanimationframe() enables you to cancel a callback previously scheduled with window.requestanimationframe.
... window.requestanimationframe() tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
... window.onmozbeforepaint an event handler property for the mozbeforepaint event, which is sent before repainting the window if the event has been requested by a call to the window.mozrequestanimationframe() method.
XRSession.visibilityState - Web APIs
the possible values of visibilitystate are: hidden the virtual scene generated by the xrsession is not currently visible to the user, so its requestanimationframe() callbacks are not being executed until thevisibilitystate changes.
...to that end, the session's requestanimationframe() callbacks are being processed at the xr device's native refresh rate and input controllers are being processed as normal.
...in order to optimize resource utilization, the user agent may be handling the session's requestanimationframe() callbacks at a throttled rate.
XRVisibilityState - Web APIs
values hidden the virtual scene generated by the xrsession is not currently visible to the user, so its requestanimationframe() callbacks are not being executed until thevisibilitystate changes.
...to that end, the session's requestanimationframe() callbacks are being processed at the xr device's native refresh rate and input controllers are being processed as normal.
...in order to optimize resource utilization, the user agent may be handling the session's requestanimationframe() callbacks at a throttled rate.
CSS Animations tips and tricks - CSS: Cascading Style Sheets
function play() { document.queryselector(".box").classname = "box"; window.requestanimationframe(function(time) { window.requestanimationframe(function(time) { document.queryselector(".box").classname = "box changing"; }); }); } this looks weird, doesn't it?
... to be sure that the styles are recalculated, we use window.requestanimationframe(), specifying a callback.
... our callback cleverly calls requestanimationframe() a second time!
Desktop mouse and keyboard controls - Game development
draw function perform the action assigned to it — move the ship left: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); if(rightpressed) { playerx += 5; } else if(leftpressed) { playerx -= 5; } if(downpressed) { playery += 5; } else if(uppressed) { playery -= 5; } ctx.drawimage(img, playerx, playery); requestanimationframe(draw); } the draw function first clears the whole canvas — we draw everything from scratch on every single frame.
...then the player's ship is drawn on the screen and the next draw is called from within the requestanimationframe.
HTMLIFrameElement.setVisible()
as an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to true, window.requestanimationframe will be called as often as necessary.
... however, if the visible state is set to false, window.requestanimationframe will be called only when there are free resources to do it.
AnalyserNode.fftSize - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount ; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dat...
AnalyserNode.frequencyBinCount - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5 - 1; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2...
AnalyserNode.getByteFrequencyData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,bar...
AnalyserNode.getByteTimeDomainData() - Web APIs
return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... analyser.fftsize = 2048; const bufferlength = analyser.fftsize; const dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; const slicewidth = width * 1.0 / bufferlength; let x = 0; canvasctx.beginpath(); for(var i = 0; i < bufferlength; i++) { const v = dataarray[i]/128.0; const y = v * heig...
AnalyserNode.getFloatFrequencyData() - Web APIs
while the audio is playing, we collect the frequency data repeatedly with requestanimationframe() and draw a "winamp bargraph style" to a <canvas> element.
...//create 2d canvas const canvas = document.createelement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerwidth; canvas.height = window.innerheight; document.body.appendchild(canvas); const canvasctx = canvas.getcontext('2d'); canvasctx.clearrect(0, 0, canvas.width, canvas.height); function draw() { //schedule next redraw requestanimationframe(draw); //get spectrum data analysernode.getfloatfrequencydata(dataarray); //draw black background canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, canvas.width, canvas.height); //draw spectrum const barwidth = (canvas.width / bufferlength) * 2.5; let posx = 0; for (let i = 0; i < bufferlength; i++) { const barheight = (dataarray[i] + 140) * 2; canvasctx.
AnalyserNode.getFloatTimeDomainData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... analyser.fftsize = 1024; var bufferlength = analyser.fftsize; console.log(bufferlength); var dataarray = new float32array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getfloattimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] * 200.0; var y = height/2 + v...
AnalyserNode.maxDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,bar...
AnalyserNode.minDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,bar...
AnalyserNode.smoothingTimeConstant - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,bar...
AnalyserNode - Web APIs
basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // get a canvas defined with id "oscilloscope" var canvas = document.getelementbyid("oscilloscope"); var canvasctx = canvas.getcontext("2d"); // draw an oscilloscope of the current audio source function draw() { requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = "rgb(200, 200, 200)"; canvasctx.fillrect(0, 0, canvas.width, canvas.height); canvasctx.linewidth = 2; canvasctx.strokestyle = "rgb(0, 0, 0)"; canvasctx.beginpath(); var slicewidth = canvas.width * 1.0 / bufferlength; var x = 0; for (var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0;...
AudioContext.getOutputTimestamp() - Web APIs
performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe loop running, which constantly outputs the contexttime and performancetime.
... play.addeventlistener('click', () => { if(!audioctx) { audioctx = new window.audiocontext(); } getdata(); source.start(0); play.setattribute('disabled', 'disabled'); raf = requestanimationframe(outputtimestamps); }); stop.addeventlistener('click', () => { source.stop(0); play.removeattribute('disabled'); cancelanimationframe(raf); }); // function to output timestamps function outputtimestamps() { let ts = audioctx.getoutputtimestamp() console.log('context time: ' + ts.contexttime + ' | performance time: ' + ts.performancetime); raf = requestanimationframe(outputtimestamps); } specifications specification status comment web audio apithe definition of 'getoutputtimestamp()' ...
BaseAudioContext.createAnalyser() - Web APIs
example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dat...
Timing element visibility with the Intersection Observer API - Web APIs
function handlerefreshinterval() { let redrawlist = []; visibleads.foreach(function(adbox) { let previoustime = adbox.dataset.totalviewtime; updateadtimer(adbox); if (previoustime != adbox.dataset.totalviewtime) { redrawlist.push(adbox); } }); if (redrawlist.length) { window.requestanimationframe(function(time) { redrawlist.foreach(function(adbox) { drawadtimer(adbox); }); }); } } the array redrawlist will be used to keep a list of all the ads which need to be redrawn during this refresh cycle, since it may not be exactly the same as the elapsed time due to system activity or because you've set the interval to something other than every 1000 milliseconds.
... finally, if there's at least one element to redraw, we use requestanimationframe() to schedule a function that will redraw each element in the redrawlist during the next animation frame.
OffscreenCanvas - Web APIs
}; you can also use requestanimationframe in workers onmessage = function(evt) { const canvas = evt.data.canvas; const gl = canvas.getcontext("webgl"); function render(time) { // ...
... requestanimationframe(render); } requestanimationframe(render); }; specifications specification status comment html living standardthe definition of 'offscreencanvas' in that specification.
Pointer Lock API - Web APIs
it also includes a check whether a requestanimationframe() call has previously been made, and if so, calls it again as required, and calls the canvasdraw() function that updates the canvas scene.
... function updateposition(e) { x += e.movementx; y += e.movementy; if (x > canvas.width + radius) { x = -radius; } if (y > canvas.height + radius) { y = -radius; } if (x < -radius) { x = canvas.width + radius; } if (y < -radius) { y = canvas.height + radius; } tracker.textcontent = "x position: " + x + ", y position: " + y; if (!animation) { animation = requestanimationframe(function() { animation = null; canvasdraw(); }); } } the canvasdraw() function draws the ball in the current x and y positions: function canvasdraw() { ctx.fillstyle = "black"; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = "#f00"; ctx.beginpath(); ctx.arc(x, y, radius, 0, degtorad(360), true); ctx.fill(); } iframe limitations pointer lock can o...
Animating objects with WebGL - Web APIs
we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to ask the browser to call the function "render" on each frame.
... requestanimationframe passes us the time in milliseconds since the page loaded.
WebGL best practices - Web APIs
use webgl.flush() when not using requestanimationframe when not using raf, (such as when using rpaf; see below) use webgl.flush() to encourage eager execution of enqueued commands.
... use requestpostanimationframe not requestanimationframe while it's well-known that apps should use requestanimationframe ("raf") instead of settimeout (et al) to redraw on-demand, what's less well-known is that non-trivial webgl apps should often not render within a raf callback.
Inputs and input sources - Web APIs
function drawframe(time, frame) { applyexternalinputs(avatar); let pose = frame.getviewerpose(avatar.referencespace); animationframerequest = session.requestanimationframe(drawframe); /* draw the frame here */ } the drawframe() function shown here is the callback invoked when it's time to draw the frame, as established by calling the the xrsession method requestanimationframe().
... after that, everything proceeds as usual, getting the viewer's pose from the updated reference frame, requesting the next frame callback through requestanimationframe(), and then continuing to set up webgl and draw the scene.
Using the Web Animations API - Web APIs
it is one of the most performant ways to animate on the web, letting the browser make its own internal optimizations without hacks, coercion, or window.requestanimationframe().
...like windowtimers.settimeout() and window.requestanimationframe(), the web animations api only takes milliseconds.
Advanced techniques: Creating and sequencing audio - Web APIs
if (lastnotedrawn != drawnote) { pads.foreach(function(el, i) { el.children[lastnotedrawn].style.bordercolor = 'hsla(0, 0%, 10%, 1)'; el.children[drawnote].style.bordercolor = 'hsla(49, 99%, 50%, 1)'; }); lastnotedrawn = drawnote; } // set up to draw again requestanimationframe(draw); } putting it all together now all that's left to do is make sure we've loaded the sample before we are able to play the instrument.
...splaying; if (isplaying) { // start playing // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } currentnote = 0; nextnotetime = audioctx.currenttime; scheduler(); // kick off scheduling requestanimationframe(draw); // start the drawing loop.
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...et topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenTop - Web APIs
WebAPIWindowscreenTop
in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...et topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenX - Web APIs
WebAPIWindowscreenX
in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...et topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny.
Window.screenY - Web APIs
WebAPIWindowscreenY
in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...et topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny.
XRFrame.getViewerPose() - Web APIs
exceptions invalidstateerror a domexception indicating that getviewerpose() was not called within the context of a callback to a session's xrsession.requestanimationframe().
... examples in this callback function for requestanimationframe(), the xrviewerpose describing the viewer's viewpoint on the world is obtained by calling getviewerpose() on the xrframe passed into the callback.
XRFrameRequestCallback - Web APIs
the xrframerequestcallback is a callback function passed into xrsession.requestanimationframe (part of webxr api) to obtain the current time and the current xrframe.
... syntax function xrframerequestcallback(time, xrframe){ // process xrframe here } xrsession.requestanimationframe(xrframerequestcallback) parameters domhighrestimestamp a timestamp corresponding to the returned xrframe.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
xrsession.requestreferencespace("local") .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, {x:0, y:0, z:1.0, w: 1.0})); xrsession.requestanimationframe(drawframe); }); in this code, we obtain a local reference space, then use getoffsetreferencespace() to create a new space whose origin is adjusted to a position given by startposition and whose orientation is looking directly along the z azis.
... then the first animation frame is requested using xrsession's requestanimationframe().
XRRigidTransform() - Web APIs
let animationframerequestid = 0; xrsession.requestreferencespace("local-floor") .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerposition, viewerorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); after requesting a reference space of type local-floor, the returned promise is eventually resolved, at which time we receive a new reference space object, refspace.
... then requestanimationframe() is called to ask for a new animation frame to draw into.
XRRigidTransform - Web APIs
it then requests the first animation frame callback by calling the session's requestanimationframe() method.
... xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); specifications specification status comment webxr device apithe definition of 'xrrigidtransform' in that specification.
XRViewport - Web APIs
these values may be passed directly into the webglrenderingcontext.viewport() method: let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); example this example sets up an animation frame callback using requestanimationframe().
... xrsession.requestanimationframe((time, xrframe) => { let viewerpose = xrframe.getviewerpose(xrreferencespace); gl.bindframebuffer(xrwebgllayer.framebuffer); for (xrview of viewerpose.views) { let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); // now we can use webgl to draw into a viewport matching // the viewer's needs } }); specifications specification status comment webxr device apithe definition of 'xrviewport' in that specification.
Performance fundamentals - Web Performance
use requestanimationframe() instead of setinterval() calls to window.setinterval() run code at a presumed frame rate that may or may not be possible under current circumstances.
... instead, you should try to use window.requestanimationframe().
Building up a basic demo with A-Frame - Game development
add this code at the end of the <script> tag: var t = 0; function render() { t += 0.01; requestanimationframe(render); cylinder.setattribute('position', '3 '+(math.sin(t*2)+1)+' 0'); } render(); we're using the render() function to update the cylinder's position on every frame.
GLSL Shaders - Game development
hree.boxgeometry(10, 10, 10); var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).textcontent, fragmentshader: document.getelementbyid( 'fragmentshader' ).textcontent }); var cube = new three.mesh(boxgeometry, shadermaterial); scene.add(cube); cube.rotation.set(0.4, 0.2, 0); function render() { requestanimationframe(render); renderer.render(scene, camera); } render(); css body { margin: 0; padding: 0; font-size: 0; } canvas { width: 100%; height: 100%; } result conclusion this article has taught the very basics of shaders.
Desktop gamepad controls - Game development
ctx.drawimage(img, playerx, playery); requestanimationframe(draw); } in this case, we are checking the four d-pad buttons (0-3) and the a button (11).
Unconventional controls - Game development
f(horizontaldegree > degreethreshold) { playerx -= 5; } else if(horizontaldegree < -degreethreshold) { playerx += 5; } if(verticaldegree > degreethreshold) { playery += 5; } else if(verticaldegree < -degreethreshold) { playery -= 5; } if(grabstrength == 1) { alert('boom!'); } ctx.drawimage(img, playerx, playery); requestanimationframe(draw); } if the horizontaldegree value is greater than our degreethreshold, which is 30 in this case, then the ship will be moved left 5 pixels on every frame.
Techniques for game development - Game development
we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe.
Move the ball - Game development
you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe().
Index - MDN Web Docs Glossary: Definitions of Web-related terms
520 frame rate (fps) animation, glossary, web performance, requestanimationframe a frame rate is the the speed at which the browser is able to recalculate, layout and paint content to the display.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
opera) ms (internet explorer and microsoft edge) property and method prefixes the prefixes for properties and methods are lower-case: webkit (chrome, safari, newer versions of opera, almost all ios browsers (including firefox for ios); basically, any webkit based browser) moz (firefox) o (old, pre-webkit, versions of opera) ms (internet explorer and microsoft edge) sample usage: var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.orequestanimationframe || window.msrequestanimationframe; learn more general knowledge vendor prefix on wikipedia ...
Introduction to web APIs - Learn web development
such apis are often combined with apis for creating animation loops (such as window.requestanimationframe()) and others to make constantly updating scenes like cartoons and games.
Browser API
this can influence resource allocation and some function usage such as requestanimationframe.
Frame rate - Firefox Developer Tools
to fix it, we might consider splitting it into pieces and running the pieces inside requestanimationframe, or even running the entire function in a worker.
Waterfall - Firefox Developer Tools
javascript functions executed in the page are labeled with the reason the function was called: script tag setinterval settimeout requestanimationframe promise callback promise init worker javascript uri event handler stack call stack, with links to functions.
CanvasRenderingContext2D.arcTo() - Web APIs
ctx.arcto(p1.x, p1.y, p2.x, p2.y, r); ctx.lineto(p2.x, p2.y); ctx.stroke(); } let t0 = 0; let rr = 0; // the radius that changes over time let a = 0; // angle let pi2 = math.pi * 2; const loop = function (t) { t0 = t / 1000; a = t0 % pi2; rr = math.abs(math.cos(a) * r); ctx.clearrect(0, 0, canvas.width, canvas.height); drawarc([p1, p2, p3], rr); drawpoints([p1, p2, p3]); requestanimationframe(loop); } loop(0); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.arcto' in that specification.
Optimizing canvas - Web APIs
with animations, use window.requestanimationframe() instead of window.setinterval() .
Page Visibility API - Web APIs
these may include: most browsers stop sending requestanimationframe() callbacks to background tabs or hidden <iframe>s in order to improve performance and battery life.
Animating textures in WebGL - Web APIs
const texture = inittexture(gl); const video = setupvideo('firefox.mp4'); var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; if (copyvideo) { updatetexture(gl, texture, video); } drawscene(gl, programinfo, buffers, texture, deltatime); requestanimationframe(render); } requestanimationframe(render); that's all there is to it!
Geometry and reference spaces in WebXR - Web APIs
when it's time to render an animation frame, the callback function specified when you called the webxr session's xrsession object's requestanimationframe() method is invoked.
WebXR Device API - Web APIs
to get an xrframe, call the session's requestanimationframe() method, providing a callback which will be called with the xrframe once available.
Web audio spatialization basics - Web APIs
alue; panner.orientationx.value = x; panner.orientationy.value = y; panner.orientationz.value = z; break; } boombox.style.transform = 'translatex('+transform.xaxis+'px) translatey('+transform.yaxis+'px) scale('+transform.zaxis+') rotatey('+transform.rotatey+'deg) rotatex('+transform.rotatex+'deg)'; const move = prevmove || {}; move.frameid = requestanimationframe(() => moveboombox(direction, move)); return move; } wiring up our controls wiring up out control buttons is comparatively simple — now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values movecontrols.foreach(function(el) { let moving; el...
XRFrame - Web APIs
WebAPIXRFrame
a webxr device api xrframe object is passed into the requestanimationframe() callback function and provides access to the information needed in order to render a single frame of animation for an xrsession describing a vr or ar sccene.
XRRigidTransform.position - Web APIs
) => { session.requestreferencespace("local-floor").then(refspacecreated); }); } else { session.requestreferencespace("viewer").then(refspacecreated); } } function refspacecreated(refspace) { if (immersivesession) { xrreferencespace = refspace; } else { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -1.5}); ); } xrsession.requestanimationframe(onframe); } after setting up the graphics context for webxr use, this begins by looking to see if a variable immersivesession is true; if so, we first request a bounded-floor reference space.
XRSession.onvisibilitychange - Web APIs
note: the visibility state of xr session affects the frame loop so callbacks registered via xrsession.requestanimationframe() might not be called.
XRSystem: requestSession() - Web APIs
xrsession.requestanimationframe(onxranimationframe); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession().
XRWebGLLayer.framebuffer - Web APIs
opaque framebuffers are considered incomplete and are not available for rendering other than while executing the requestanimationframe() callback.
XRWebGLLayer.getViewport() - Web APIs
example this example demonstrates in part what the callback for the requestanimationframe() function might look like, using getviewport() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered.
XRWebGLLayer - Web APIs
let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); rendering every view in a frame each time the gpu is ready to render the scene to the xr device, the xr runtime calls the function you specified when you called the xrsession method requestanimationframe() to ask to render the frame.
Audio and video manipulation - Developer guides
for efficiency, you should consider using requestanimationframe() instead of settimeout() when running on browsers that support it.
HTML5 - Developer guides
WebGuideHTMLHTML5
requestanimationframe allows control of animations rendering to obtain optimal performance.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
mousedown = function() { pressed = true; }; canvas.onmouseup = function() { pressed = false; } clearbtn.onclick = function() { ctx.fillstyle = 'rgb(0,0,0)'; ctx.fillrect(0,0,width,height); } function draw() { if(pressed) { ctx.fillstyle = colorpicker.value; ctx.beginpath(); ctx.arc(curx, cury-85, sizepicker.value, degtorad(0), degtorad(360), false); ctx.fill(); } requestanimationframe(draw); } draw(); specifications specification status comments html living standardthe definition of '<input type="button">' in that specification.