Animations with JS

Rate this content
Bookmark

Creating different animation effects like bouncing, typing with vanilla javascript. Looking at several approaches of creating animations with time based functions and Request Animation frame.

This talk has been presented at JSNation 2022, check out the latest edition of this JavaScript Conference.

FAQ

Animation is a way to communicate motion. It involves showing images in rapid succession to create the perception of motion, similar to a flip book.

Frame rate is the number of frames shown in one second. For smooth animations on the web, the target is usually 60 frames per second.

You can achieve animations on the web using JavaScript, CSS transitions, CSS animations, and the Web Animations API.

CSS transitions define starting and ending points and require an action to trigger, while CSS animations can define intermediate points using keyframes and can run in a loop.

JavaScript allows for more control over animations, such as simulating real-world scenarios and controlling interpolation, which may not be possible with CSS.

The requestAnimationFrame method tells the browser to perform an animation and synchronizes it with the browser's paint cycle, ensuring smoother and more efficient animations.

SetInterval and setTimeout can have inconsistent timing, are not synchronized with the browser's paint cycle, and can consume more CPU and battery, especially when the tab is inactive.

You can optimize animations by incrementing positions based on the time passed rather than a fixed increment, ensuring consistent speed across devices with different frame rates.

The Web Animations API is a powerful tool for creating animations, inspired by CSS animations and transitions. It allows for dynamic setting of values and runs on a composite thread, providing performant animations.

Use CSS animations for simpler animations where you don't need much control, as they are more performant. Use JavaScript animations when you need more control over the animation, such as controlling interpolation.

Aashima Ahuja
Aashima Ahuja
19 min
16 Jun, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's talk is about animations in Javascript, covering frame rates and different methods like CSS transitions and animations. JavaScript provides more control over animations, allowing interpolation and simulation of real-world scenarios. Different approaches to animating a box from zero to 100 pixels are discussed, including for loops, timers, and the web animations API. Request Animation Frame is highlighted as a solution for consistent and smooth animations. The Web Animations API is introduced as a powerful tool alongside CSS animations and transitions, although it has limited browser support.
Available in Español: Animaciones con JS

1. Introduction to Animations in Javascript

Short description:

Today's talk is about animations in Javascript. We will discuss frame rates and how they affect animation smoothness. Different methods like CSS transitions and animations can be used to achieve web animations.

So how's everyone doing so far? Are you guys enjoying the talk? Nice. Any back end developers here? Making some noise? Any motion designers? Okay, nobody.

So today my topic is animations. Animations in simple word is just a way to communicate motion. So while this concept was introduced into movies first before it was brought into web, but people have been trying to find ways to communicate motion from a very long time. How many of you remember this flip book, where we would draw a bunch of drawings and flip them together really fast to create a perception of motion.

So the idea is that when images are shown fast enough, our brain loses the ability to see individual frames and blends them together into a single moving image. But in digital world, we have frames. Each frame has a drawing and the idea is similar to the flip book, it's just put those frames together really fast to create the perception of motion.

Hello, my name is Ashima. I'm a friend and engineer at Miro, and today I'm particularly going to be talking about animations in Javascript. So all of you must have heard this term, frame rates, frames per second. I first heard about it in movies. So frame rate is the number of frames shown in one second. So if we show 60 frames in one second, it becomes 60 frames per second, and more the frames we show in one second, the smoother the animation gets. In order to render smooth animations on web, we target 60 frames per second. But that depends a lot on the device which you are using. For instance, if you're using a mobile phone, there is a high likely chance that it's running on a frequency lower than 60 hertz. So the frame rate would be like 30 frames per second or whatever the device supports.

In web, we can achieve animations using JavaScript, using CSS, using CSS transitions and animations. In CSS transitions, you usually define two points. One is the starting point and the other one is the ending point. Whatever happens in between is controlled by the browser. So this is what we call interpolation. In CSS transitions, you usually need an action to trigger. So you would use a hover or a click. And you cannot run them in loop. So we have CSS animations. And in CSS animations, you can define intermediate points as well using key frames, apart from just defining the starting and ending point. And yes, the interpolation, again, is controlled by the browser.

2. Controlling Animations in JavaScript

Short description:

Sometimes CSS is not enough to achieve the desired animations in JavaScript. JavaScript provides more control over animations, allowing interpolation and simulation of real-world scenarios. There are different approaches to animating a box from zero to 100 pixels, including using a for loop, timers like set interval and set timeout, the requestAnimationFrame, and the modern web animations API. When using a for loop, the browser renders the box directly at 100 pixels instead of incrementally updating its position due to how the event loop works. Timers like set interval and set timeout can be used to solve this problem by executing a callback after a specified delay.

That's how it would move between different states. But sometimes it's not just possible to do everything with CSS. I know the browser does a lot for us when it comes to animations. But when we need more control over the animations, we need to use JavaScript. And so JavaScript allows you to control the interpolation and to simulate real world scenarios.

For instance, free falling of an object, or like falling of a snow. So let's suppose you are given this problem, that you want to animate a box from zero to 100 pixels. How many of you have encountered this in your interviews? I did. And I failed. But today we will see that there are a couple of, there can be a couple of approaches to solve this, basically. So you can use For Loop if you are new to JavaScript. You can use timers, set intervals, set timeout. You can also use the quest animation frame, and then the modern web animations API.

So if you're using For Loop, so you can run it from zero to 100 pixels, and tell your browser, okay, browser, render this to me at a particular position. But this does not work. What happens in this case is the box gets rendered directly at 100 pixels. But this is not what you want. You want to update the position incrementally. So the expectation is that browser would do something like this, like show it at 0, 1, 2, and then 100. But the reality is that the line gets executed, is translate X 100 pixels. Evil browser. So this is because how event loop works. I really like this diagram from Jake. If you haven't seen the talk, event loop, it's really a must-watch. So what is happening here is that the for loop gets executed as a task. And after the entire for loop gets executed, browser goes to calculate the styles, render the layout, and then do the paint. And that is why we see the translate x 100 pixels only getting executed.

Another way to solve this problem is using timers. You can use set interval and set timeout. Both of these function take a callback and a delay time after which the callback would be executed.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

The Whimsical Potential of JavaScript Frameworks
React Summit US 2023React Summit US 2023
28 min
The Whimsical Potential of JavaScript Frameworks
Top Content
Watch video: The Whimsical Potential of JavaScript Frameworks
The speaker discusses the whimsical and detailed work of Stripe, particularly their interactive and dynamic pages. They explain the use of React for building whimsical details and tracking mouse position. The speaker introduces React Spring for smooth animation and React3 Fiber for creating a 3D egg model. They also mention the use of Framer Motion and React server components for animating CSS properties.
Emotional & Functional UI Animations in React
React Day Berlin 2022React Day Berlin 2022
28 min
Emotional & Functional UI Animations in React
Today's Talk discussed the importance of UI animations in React, both functional and emotional. Examples were given using CSS and Framer Motion, with a focus on user feedback and accessibility. Design guidelines and animation usage were highlighted, as well as the consideration of negative emotions in animations. The Talk also touched on designing 404 error pages and concluded with gratitude to the audience and organizers.
Keep Scrolling
JSNation Live 2021JSNation Live 2021
33 min
Keep Scrolling
Scroll animations can enhance user experience when done properly, but should not distract from important information. CSS, JavaScript, and plugins like Scroll Trigger can be used to achieve scroll animations. GreenSock's ScrollTrigger provides a powerful JavaScript animation library for more complex animations. It is important to consider accessibility and provide reduced motion fallbacks. CodePen and GreenSock's documentation are valuable resources for learning and inspiration in creative coding.
React Native Animations Should Be Fun
React Advanced Conference 2022React Advanced Conference 2022
28 min
React Native Animations Should Be Fun
This talk is about animations in React Native, specifically focusing on React Native Reanimated. It covers the use of interpolations and extrapolations in animations, animating items in a carousel or list, sticky elements and interpolation, and fluidity and layout animations. The talk provides valuable tips and tricks for creating performant animations and explores the use of math formulas for natural movements.
Animation and Vue.js
Vue.js London Live 2021Vue.js London Live 2021
32 min
Animation and Vue.js
Today's Talk covers animation in Vue JS apps, including CSS animations, JavaScript animations using the GSAP library, and handling multiple elements with transition groups. The Talk also discusses different kinds of movements, state transitions, and animating numbers and SVGs. Overall, it provides a comprehensive overview of animation techniques and tools for enhancing Vue JS apps.
Lessons Learnt from Building Interactive React Applications
React Summit Remote Edition 2021React Summit Remote Edition 2021
35 min
Lessons Learnt from Building Interactive React Applications
Animations can enhance the user experience and provide context in interface design. Using frame and motion in React can create smooth fade-in effects and improve navigation. Optimistic updates and instant comment appearance can eliminate waiting time and improve user experience. Motion can be used in multiple ways to give context and enhance user experience. Accessibility and performance should be considered when implementing animations. Choosing the right library, such as frame of motion or React Spring, can simplify animation implementation. Animations can enhance perceived performance and influence users' perception of speed.

Workshops on related topic

How to make amazing generative art with simple JavaScript code
JS GameDev Summit 2022JS GameDev Summit 2022
165 min
How to make amazing generative art with simple JavaScript code
Top Content
WorkshopFree
Frank Force
Frank Force
Instead of manually drawing each image like traditional art, generative artists write programs that are capable of producing a variety of results. In this workshop you will learn how to create incredible generative art using only a web browser and text editor. Starting with basic concepts and building towards advanced theory, we will cover everything you need to know.