mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-13 22:00:19 -04:00
feat(curriculum): Add interactive examples to requestAnimationFrame lesson (#63475)
This commit is contained in:
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: what-is-the-requestanimationframe-api-and-how-can-it-be-used-to-set-up-an-animation-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
Creating smooth animations on a web page can be tricky, especially if you're not sure how to handle timing properly. The great news is that the `requestAnimationFrame()` API makes it easier.
|
||||
|
||||
@@ -48,14 +48,16 @@ requestAnimationFrame(animate);
|
||||
|
||||
The loop will continue until you stop it.
|
||||
|
||||
Now, let's take a look at another example. The HTML for this example is a `div` element with the text `freeCodeCamp is Awesome`:
|
||||
Now, let's take a look at another example. The HTML for this example is a `div` element with the text `freeCodeCamp is Awesome`. The CSS makes the `div` a rectangle and hides anything that goes out of the viewport on the left or right. The JavaScript code moves the rectangle `2px` to the right at every call of `requestAnimationFrame(animate)` with the `animate` function as a callback:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="styles.css" />
|
||||
<div id="rect" class="rect">freeCodeCamp is Awesome</div>
|
||||
<script src="index.js"></script>
|
||||
```
|
||||
|
||||
This is the CSS that makes the `div` a rectangle and hides anything that goes out of the viewport on the left or right:
|
||||
|
||||
```css
|
||||
body {
|
||||
overflow-x: hidden;
|
||||
@@ -75,13 +77,9 @@ body {
|
||||
}
|
||||
```
|
||||
|
||||
This is the commented JavaScript that moves the rectangle `2px` to the right at every call of `requestAnimationFrame(animate)` with the `animate` function as a callback:
|
||||
|
||||
```js
|
||||
// reference the rectangle
|
||||
const rect = document.getElementById("rect");
|
||||
|
||||
// start with a position of 0
|
||||
let position = 0;
|
||||
|
||||
function update() {
|
||||
@@ -89,8 +87,6 @@ function update() {
|
||||
rect.style.left = position + "px";
|
||||
position += 2;
|
||||
|
||||
// Reset the position when the rectangle reaches
|
||||
// the right side of the screen
|
||||
if (position > window.innerWidth) {
|
||||
// Move the rectangle just outside the left side of the screen
|
||||
position = -rect.offsetWidth;
|
||||
@@ -98,7 +94,6 @@ function update() {
|
||||
}
|
||||
|
||||
function animate() {
|
||||
// Update the position
|
||||
update();
|
||||
|
||||
//request the next frame
|
||||
@@ -109,6 +104,8 @@ function animate() {
|
||||
requestAnimationFrame(animate);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The result in the browser will be an animated title card floating across the screen.
|
||||
|
||||
# --questions--
|
||||
|
||||
Reference in New Issue
Block a user