From e8edfe678caeb6a386ba1b4e14a39853286b1c2c Mon Sep 17 00:00:00 2001 From: Teva Henry <35941084+TevaHenry@users.noreply.github.com> Date: Tue, 12 Oct 2021 20:17:08 +1300 Subject: [PATCH] Translate JavaScript animations --- .../3-js-animation/1-animate-ball/solution.md | 8 +- .../3-js-animation/1-animate-ball/task.md | 4 +- .../2-animate-ball-hops/solution.md | 14 +- .../2-animate-ball-hops/task.md | 8 +- 7-animation/3-js-animation/article.md | 244 +++++++++--------- 5 files changed, 139 insertions(+), 139 deletions(-) diff --git a/7-animation/3-js-animation/1-animate-ball/solution.md b/7-animation/3-js-animation/1-animate-ball/solution.md index 0dc67b8bd..8cf502686 100644 --- a/7-animation/3-js-animation/1-animate-ball/solution.md +++ b/7-animation/3-js-animation/1-animate-ball/solution.md @@ -1,10 +1,10 @@ -To bounce we can use CSS property `top` and `position:absolute` for the ball inside the field with `position:relative`. +Pour rebondir, nous pouvons utiliser les propriétés CSS `top` et `position:absolute` pour la balle à l'intérieur du champ avec `position:relative`. -The bottom coordinate of the field is `field.clientHeight`. The CSS `top` property refers to the upper edge of the ball. So it should go from `0` till `field.clientHeight - ball.clientHeight`, that's the final lowest position of the upper edge of the ball. +La coordonnée du bas du champ est `field.clientHeight`. La propriété CSS `top` fait référence au bord supérieur de la balle. Elle doit donc aller de `0` à `field.clientHeight - ball.clientHeight`, c'est-à-dire la position finale la plus basse du bord supérieur de la balle. -To get the "bouncing" effect we can use the timing function `bounce` in `easeOut` mode. +Pour obtenir l'effet de "rebond", nous pouvons utiliser la fonction de timing `bounce` en mode `easeOut`. -Here's the final code for the animation: +Voici le code final de l'animation : ```js let to = field.clientHeight - ball.clientHeight; diff --git a/7-animation/3-js-animation/1-animate-ball/task.md b/7-animation/3-js-animation/1-animate-ball/task.md index 903e82384..13c46bed9 100644 --- a/7-animation/3-js-animation/1-animate-ball/task.md +++ b/7-animation/3-js-animation/1-animate-ball/task.md @@ -2,8 +2,8 @@ importance: 5 --- -# Animate the bouncing ball +# Animer la balle rebondissante -Make a bouncing ball. Click to see how it should look: +Créez une balle rebondissante. Cliquez pour voir à quoi elle doit ressembler : [iframe height=250 src="https://github.com/solution"] diff --git a/7-animation/3-js-animation/2-animate-ball-hops/solution.md b/7-animation/3-js-animation/2-animate-ball-hops/solution.md index d47387e30..5cbf093cf 100644 --- a/7-animation/3-js-animation/2-animate-ball-hops/solution.md +++ b/7-animation/3-js-animation/2-animate-ball-hops/solution.md @@ -1,18 +1,18 @@ -In the task we had only one property to animate. Now we need one more: `elem.style.left`. +Dans la tâche , nous n'avions qu'une seule propriété à animer. Maintenant, nous avons besoin d'une supplémentaire : `elem.style.left`. -The horizontal coordinate changes by another law: it does not "bounce", but gradually increases shifting the ball to the right. +La coordonnée horizontale change selon une autre loi : elle ne "rebondit" pas, mais augmente progressivement en déplaçant la balle vers la droite. -We can write one more `animate` for it. +Nous pouvons écrire un autre `animate` pour elle. -As the time function we could use `linear`, but something like `makeEaseOut(quad)` looks much better. +Comme fonction de temporisation, nous pourrions utiliser `linear`, mais quelque chose comme `makeEaseOut(quad)` semble bien mieux. -The code: +Le code : ```js let height = field.clientHeight - ball.clientHeight; let width = 100; -// animate top (bouncing) +// animer top (rebondissement) animate({ duration: 2000, timing: makeEaseOut(bounce), @@ -21,7 +21,7 @@ animate({ } }); -// animate left (moving to the right) +// animer left (déplacement vers la droite) animate({ duration: 2000, timing: makeEaseOut(quad), diff --git a/7-animation/3-js-animation/2-animate-ball-hops/task.md b/7-animation/3-js-animation/2-animate-ball-hops/task.md index fdc26c8da..0a99b0e57 100644 --- a/7-animation/3-js-animation/2-animate-ball-hops/task.md +++ b/7-animation/3-js-animation/2-animate-ball-hops/task.md @@ -2,12 +2,12 @@ importance: 5 --- -# Animate the ball bouncing to the right +# Animer la balle pour qu'elle rebondisse vers la droite. -Make the ball bounce to the right. Like this: +Faites rebondir la balle vers la droite. Comme ceci : [iframe height=250 src="https://github.com/solution"] -Write the animation code. The distance to the left is `100px`. +Écrivez le code d'animation. La distance à gauche est de `100px`. -Take the solution of the previous task as the source. +Prenez la solution de la tâche précédente comme source. diff --git a/7-animation/3-js-animation/article.md b/7-animation/3-js-animation/article.md index 517b2481b..7104f0ecf 100644 --- a/7-animation/3-js-animation/article.md +++ b/7-animation/3-js-animation/article.md @@ -1,63 +1,63 @@ -# JavaScript animations +# Animations JavaScript -JavaScript animations can handle things that CSS can't. +Les animations JavaScript peuvent gérer des choses que CSS ne peut pas gérer. -For instance, moving along a complex path, with a timing function different from Bezier curves, or an animation on a canvas. +Par exemple, le déplacement le long d'un chemin complexe, avec une fonction de temporisation différente des courbes de Bézier, ou une animation sur un élément canvas. -## Using setInterval +## Utilisation de setInterval -An animation can be implemented as a sequence of frames -- usually small changes to HTML/CSS properties. +Une animation peut être implémentée sous la forme d'une séquence d'images -- généralement de petites modifications des propriétés HTML/CSS. -For instance, changing `style.left` from `0px` to `100px` moves the element. And if we increase it in `setInterval`, changing by `2px` with a tiny delay, like 50 times per second, then it looks smooth. That's the same principle as in the cinema: 24 frames per second is enough to make it look smooth. +Par exemple, en changeant `style.left` de `0px` à `100px`, on déplace l'élément. Et si nous l'augmentons dans `setInterval`, en changeant de `2px` avec un minuscule retard, comme 50 fois par seconde, alors cela semble fluide. C'est le même principe qu'au cinéma : 24 images par seconde suffisent pour que l'image soit fluide. -The pseudo-code can look like this: +Le pseudo-code peut ressembler à ceci : ```js let timer = setInterval(function() { if (animation complete) clearInterval(timer); else increase style.left by 2px -}, 20); // change by 2px every 20ms, about 50 frames per second +}, 20); // changement de 2px toutes les 20ms, environ 50 images par seconde ``` -More complete example of the animation: +Exemple plus complet de l'animation : ```js -let start = Date.now(); // remember start time +let start = Date.now(); // mémoriser l'heure de début let timer = setInterval(function() { - // how much time passed from the start? + // combien de temps s'est écoulé depuis le début ? let timePassed = Date.now() - start; if (timePassed >= 2000) { - clearInterval(timer); // finish the animation after 2 seconds + clearInterval(timer); // terminer l'animation après 2 secondes return; } - // draw the animation at the moment timePassed + // dessiner l'animation à l'instant timePassed draw(timePassed); }, 20); -// as timePassed goes from 0 to 2000 -// left gets values from 0px to 400px +// à mesure que timePassed passe de 0 à 2000 +// left obtient des valeurs de 0px à 400px function draw(timePassed) { train.style.left = timePassed / 5 + 'px'; } ``` -Click for the demo: +Cliquez pour la démo : [codetabs height=200 src="https://github.com/move"] -## Using requestAnimationFrame +## Utilisation de requestAnimationFrame -Let's imagine we have several animations running simultaneously. +Imaginons que nous ayons plusieurs animations fonctionnant simultanément. -If we run them separately, then even though each one has `setInterval(..., 20)`, then the browser would have to repaint much more often than every `20ms`. +Si nous les exécutons séparément, alors même si chacune d'entre elles possède `setInterval(..., 20)`, le navigateur devra repeindre bien plus souvent que toutes les `20ms`. -That's because they have different starting time, so "every 20ms" differs between different animations. The intervals are not aligned. So we'll have several independent runs within `20ms`. +C'est parce qu'elles ont un temps de départ différent, donc "toutes les 20 ms" diffère entre les différentes animations. Les intervalles ne sont pas alignés. Nous aurons donc plusieurs animations indépendantes dans un intervalle de `20ms`. -In other words, this: +En d'autres termes, ceci : ```js setInterval(function() { @@ -67,40 +67,40 @@ setInterval(function() { }, 20) ``` -...Is lighter than three independent calls: +...Est plus léger que trois appels indépendants : ```js -setInterval(animate1, 20); // independent animations -setInterval(animate2, 20); // in different places of the script +setInterval(animate1, 20); // animations indépendantes +setInterval(animate2, 20); // à différents endroits du script setInterval(animate3, 20); ``` -These several independent redraws should be grouped together, to make the redraw easier for the browser and hence load less CPU load and look smoother. +Ces redessinages indépendants doivent être regroupés, afin de faciliter le redessinage pour le navigateur et donc de réduire la charge du processeur et d'obtenir un aspect plus fluide. -There's one more thing to keep in mind. Sometimes CPU is overloaded, or there are other reasons to redraw less often (like when the browser tab is hidden), so we really shouldn't run it every `20ms`. +Il y a une autre chose à garder en tête. Parfois, le CPU est surchargé, ou il y a d'autres raisons de redessiner moins souvent (comme lorsque l'onglet du navigateur est caché), donc nous ne devrions vraiment pas le lancer tous les `20ms`. -But how do we know about that in JavaScript? There's a specification [Animation timing](http://www.w3.org/TR/animation-timing/) that provides the function `requestAnimationFrame`. It addresses all these issues and even more. +Mais comment le savoir en JavaScript ? Il existe une spécification [Animation timing](http://www.w3.org/TR/animation-timing/) qui fournit la fonction `requestAnimationFrame`. Elle répond à toutes ces questions et même plus. -The syntax: +La syntaxe : ```js let requestId = requestAnimationFrame(callback) ``` -That schedules the `callback` function to run in the closest time when the browser wants to do animation. +Cela programme la fonction `callback` pour qu'elle s'exécute au moment le plus proche où le navigateur veut faire une animation. -If we do changes in elements in `callback` then they will be grouped together with other `requestAnimationFrame` callbacks and with CSS animations. So there will be one geometry recalculation and repaint instead of many. +Si nous modifions des éléments dans `callback`, ils seront regroupés avec d'autres callbacks `requestAnimationFrame` et avec les animations CSS. Il y aura donc un seul recalcul de la géométrie et un seul repeint au lieu de plusieurs. -The returned value `requestId` can be used to cancel the call: +La valeur retournée `requestId` peut être utilisée pour annuler l'appel : ```js -// cancel the scheduled execution of callback +// annuler l'exécution programmée du callback cancelAnimationFrame(requestId); ``` -The `callback` gets one argument -- the time passed from the beginning of the page load in microseconds. This time can also be obtained by calling [performance.now()](mdn:api/Performance/now). +Le `callback` reçoit un argument -- le temps écoulé depuis le début du chargement de la page en microsecondes. Ce temps peut aussi être obtenu en appelant [performance.now()](https://developer.mozilla.org/fr/docs/Web/API/Performance/now). -Usually `callback` runs very soon, unless the CPU is overloaded or the laptop battery is almost discharged, or there's another reason. +Habituellement, `callback` s'exécute très rapidement, à moins que le CPU soit surchargé ou que la batterie de l'ordinateur portable soit presque déchargée, ou qu'il y ait une autre raison. -The code below shows the time between first 10 runs for `requestAnimationFrame`. Usually it's 10-20ms: +Le code ci-dessous montre le temps entre les 10 premières exécutions de `requestAnimationFrame`. Habituellement, c'est 10-20ms : ```html run height=40 refresh ``` -## Structured animation +## Animation structurée -Now we can make a more universal animation function based on `requestAnimationFrame`: +Maintenant nous pouvons faire une fonction d'animation plus universelle basée sur `requestAnimationFrame` : ```js function animate({timing, draw, duration}) { @@ -126,14 +126,14 @@ function animate({timing, draw, duration}) { let start = performance.now(); requestAnimationFrame(function animate(time) { - // timeFraction goes from 0 to 1 + // timeFraction passe de 0 à 1 let timeFraction = (time - start) / duration; if (timeFraction > 1) timeFraction = 1; - // calculate the current animation state + // calculer l'état courant de l'animation let progress = timing(timeFraction) - draw(progress); // draw it + draw(progress); // dessinez-le if (timeFraction < 1) { requestAnimationFrame(animate); @@ -143,15 +143,15 @@ function animate({timing, draw, duration}) { } ``` -Function `animate` accepts 3 parameters that essentially describes the animation: +La fonction `animate` accepte 3 paramètres qui décrivent essentiellement l'animation : -`duration` -: Total time of animation. Like, `1000`. +`duration`` +: Durée totale de l'animation. Par exemple, `1000`. `timing(timeFraction)` -: Timing function, like CSS-property `transition-timing-function` that gets the fraction of time that passed (`0` at start, `1` at the end) and returns the animation completion (like `y` on the Bezier curve). +: Fonction de chronométrage, comme la propriété CSS `transition-timing-function` qui obtient la fraction de temps qui s'est écoulée (`0` au début, `1` à la fin) et renvoie la fin de l'animation (comme `y` sur la courbe de Bézier). - For instance, a linear function means that the animation goes on uniformly with the same speed: + Par exemple, une fonction linéaire signifie que l'animation se déroule uniformément avec la même vitesse : ```js function linear(timeFraction) { @@ -159,33 +159,33 @@ Function `animate` accepts 3 parameters that essentially describes the animation } ``` - It's graph: + Le graph : ![](linear.svg) - That's just like `transition-timing-function: linear`. There are more interesting variants shown below. + C'est comme `transition-timing-function : linear`. Il existe d'autres variantes intéressantes présentées ci-dessous. `draw(progress)` -: The function that takes the animation completion state and draws it. The value `progress=0` denotes the beginning animation state, and `progress=1` -- the end state. +: La fonction qui prend l'état final de l'animation et le dessine. La valeur `progress=0` indique l'état de début d'animation, et `progress=1` -- l'état de fin. - This is that function that actually draws out the animation. + Il s'agit de la fonction qui dessine réellement l'animation. - It can move the element: + Elle peut déplacer l'élément : ```js function draw(progress) { train.style.left = progress + 'px'; } ``` - ...Or do anything else, we can animate anything, in any way. + ...Ou faire n'importe quoi d'autre, nous pouvons animer toute chose, de n'importe quelle manière. -Let's animate the element `width` from `0` to `100%` using our function. +Animons l'élément `width` de `0` à `100%` en utilisant notre fonction. -Click on the element for the demo: +Cliquez sur l'élément pour la démonstration : [codetabs height=60 src="https://github.com/width"] -The code for it: +Le code pour cela : ```js animate({ @@ -199,19 +199,19 @@ animate({ }); ``` -Unlike CSS animation, we can make any timing function and any drawing function here. The timing function is not limited by Bezier curves. And `draw` can go beyond properties, create new elements for like fireworks animation or something. +Contrairement à l'animation CSS, nous pouvons créer ici n'importe quelle fonction de temporisation et n'importe quelle fonction draw (de dessinnage). La fonction de timing n'est pas limitée par les courbes de Bézier. Et `draw` peut aller au-delà des propriétés, créer de nouveaux éléments pour une animation de feu d'artifice ou autre. -## Timing functions +## Fonctions de temporisation -We saw the simplest, linear timing function above. +Nous avons vu la fonction de temporisation la plus simple, linéaire, ci-dessus. -Let's see more of them. We'll try movement animations with different timing functions to see how they work. +Nous allons en voir d'autres. Nous allons essayer des animations de mouvements avec différentes fonctions de temporisation pour voir comment elles fonctionnent. -### Power of n +### Puissance de n -If we want to speed up the animation, we can use `progress` in the power `n`. +Si nous voulons accélérer l'animation, nous pouvons utiliser `progress` à la puissance `n`. -For instance, a parabolic curve: +Par exemple, une courbe parabolique : ```js function quad(timeFraction) { @@ -219,27 +219,27 @@ function quad(timeFraction) { } ``` -The graph: +Le graph : ![](quad.svg) -See in action (click to activate): +Voir en action (cliquer pour activer) : [iframe height=40 src="https://github.com/quad" link] -...Or the cubic curve or even greater `n`. Increasing the power makes it speed up faster. +...Ou la courbe cubique ou encore un `n` plus grand. En augmentant la puissance, on accélère la vitesse. -Here's the graph for `progress` in the power `5`: +Voici le graphique de `progress` à la puissance `5` : ![](quint.svg) -In action: +En action : [iframe height=40 src="https://github.com/quint" link] -### The arc +### L'arc -Function: +Fonction : ```js function circ(timeFraction) { @@ -247,19 +247,19 @@ function circ(timeFraction) { } ``` -The graph: +Le graph: ![](circ.svg) [iframe height=40 src="https://github.com/circ" link] -### Back: bow shooting +### Back : tir à l'arc -This function does the "bow shooting". First we "pull the bowstring", and then "shoot". +Cette fonction effectue le "tir à l'arc" (bow shooting). On commence par "tirer la corde de l'arc", puis on "tire". -Unlike previous functions, it depends on an additional parameter `x`, the "elasticity coefficient". The distance of "bowstring pulling" is defined by it. +Contrairement aux fonctions précédentes, elle dépend d'un paramètre supplémentaire `x`, le "coefficient d'élasticité". La distance de "traction de la corde de l'arc" est définie par celui-ci. -The code: +Le code : ```js function back(x, timeFraction) { @@ -267,19 +267,19 @@ function back(x, timeFraction) { } ``` -**The graph for `x = 1.5`:** +**Le graph pour `x = 1.5`:** ![](back.svg) -For animation we use it with a specific value of `x`. Example for `x = 1.5`: +Pour l'animation, nous l'utilisons avec une valeur spécifique de `x`. Exemple pour `x = 1.5` : [iframe height=40 src="https://github.com/back" link] ### Bounce -Imagine we are dropping a ball. It falls down, then bounces back a few times and stops. +Imaginez que nous lâchons une balle. Elle tombe, puis rebondit plusieurs fois et s'arrête. -The `bounce` function does the same, but in the reverse order: "bouncing" starts immediately. It uses few special coefficients for that: +La fonction `bounce` fait la même chose, mais dans l'ordre inverse : Le "rebond" commence immédiatement. Elle utilise quelques coefficients spéciaux pour cela : ```js function bounce(timeFraction) { @@ -291,13 +291,13 @@ function bounce(timeFraction) { } ``` -In action: +En action : [iframe height=40 src="https://github.com/bounce" link] -### Elastic animation +### Animation élastique -One more "elastic" function that accepts an additional parameter `x` for the "initial range". +Une fonction "élastique" de plus qui accepte un paramètre supplémentaire `x` pour la "portée initiale". ```js function elastic(x, timeFraction) { @@ -305,31 +305,31 @@ function elastic(x, timeFraction) { } ``` -**The graph for `x=1.5`:** +**Le graph pour `x=1.5`:** ![](elastic.svg) -In action for `x=1.5`: +En action pour `x=1.5` : [iframe height=40 src="https://github.com/elastic" link] -## Reversal: ease* +## Reversal : ease* -So we have a collection of timing functions. Their direct application is called "easeIn". +Nous avons donc une collection de fonctions de temporisation. Leur application directe est appelée "easeIn". -Sometimes we need to show the animation in the reverse order. That's done with the "easeOut" transform. +Parfois, nous avons besoin de montrer l'animation dans l'ordre inverse. C'est possible avec la transformation "easeOut". ### easeOut -In the "easeOut" mode the `timing` function is put into a wrapper `timingEaseOut`: +Dans le mode "easeOut", la fonction `timing` est placée dans un wrapper `timingEaseOut` : ```js timingEaseOut(timeFraction) = 1 - timing(1 - timeFraction) ``` -In other words, we have a "transform" function `makeEaseOut` that takes a "regular" timing function and returns the wrapper around it: +En d'autres termes, nous avons une fonction de "transformation" `makeEaseOut` qui prend une fonction de temporisation "régulière" et renvoie le wrapper qui l'entoure : ```js -// accepts a timing function, returns the transformed variant +// accepte une fonction de temporisation, renvoie la variante transformée function makeEaseOut(timing) { return function(timeFraction) { return 1 - timing(1 - timeFraction); @@ -337,42 +337,42 @@ function makeEaseOut(timing) { } ``` -For instance, we can take the `bounce` function described above and apply it: +Par exemple, nous pouvons prendre la fonction `bounce` décrite ci-dessus et l'appliquer : ```js let bounceEaseOut = makeEaseOut(bounce); ``` -Then the bounce will be not in the beginning, but at the end of the animation. Looks even better: +Ainsi, le rebond ne sera pas au début, mais à la fin de l'animation. C'est encore mieux : [codetabs src="https://github.com/bounce-easeout"] -Here we can see how the transform changes the behavior of the function: +Ici, nous pouvons voir comment la transformation change le comportement de la fonction : ![](bounce-inout.svg) -If there's an animation effect in the beginning, like bouncing -- it will be shown at the end. +S'il y a un effet d'animation au début, comme le rebondissement -- il sera affiché à la fin. -In the graph above the regular bounce has the red color, and the easeOut bounce is blue. +Dans le graphique ci-dessus, le regular bounce a la couleur rouge, et le easeOut bounce est bleu. -- Regular bounce -- the object bounces at the bottom, then at the end sharply jumps to the top. -- After `easeOut` -- it first jumps to the top, then bounces there. +- Regular bounce -- l'objet rebondit en bas, puis à la fin saute brusquement en haut. +- Après `easeOut` -- il saute d'abord vers le haut, puis rebondit là. ### easeInOut -We also can show the effect both in the beginning and the end of the animation. The transform is called "easeInOut". +Nous pouvons également montrer l'effet à la fois au début et à la fin de l'animation. La transformation est appelée "easeInOut". -Given the timing function, we calculate the animation state like this: +Étant donné la fonction de temporisation, nous calculons l'état de l'animation comme suit : ```js -if (timeFraction <= 0.5) { // first half of the animation +if (timeFraction <= 0.5) { // première moitié de l'animation return timing(2 * timeFraction) / 2; -} else { // second half of the animation +} else { // deuxième moitié de l'animation return (2 - timing(2 * (1 - timeFraction))) / 2; } ``` -The wrapper code: +Le code du wrapper : ```js function makeEaseInOut(timing) { @@ -387,37 +387,37 @@ function makeEaseInOut(timing) { bounceEaseInOut = makeEaseInOut(bounce); ``` -In action, `bounceEaseInOut`: +En action, `bounceEaseInOut` : [codetabs src="https://github.com/bounce-easeinout"] -The "easeInOut" transform joins two graphs into one: `easeIn` (regular) for the first half of the animation and `easeOut` (reversed) -- for the second part. +La transformation "easeInOut" joint deux graphiques en un seul : `easeIn` (régulier) pour la première moitié de l'animation et `easeOut` (inversé) -- pour la deuxième moitié. -The effect is clearly seen if we compare the graphs of `easeIn`, `easeOut` and `easeInOut` of the `circ` timing function: +L'effet est clairement visible si l'on compare les graphiques de `easeIn`, `easeOut` et `easeInOut` de la fonction de temporisation `circ` : ![](circ-ease.svg) -- Red is the regular variant of `circ` (`easeIn`). +- Red est la variante régulière de `circ` (`easeIn`). - Green -- `easeOut`. - Blue -- `easeInOut`. -As we can see, the graph of the first half of the animation is the scaled down `easeIn`, and the second half is the scaled down `easeOut`. As a result, the animation starts and finishes with the same effect. +Comme nous pouvons le voir, le graphique de la première moitié de l'animation est le `easeIn` atténué, et la seconde moitié est le `easeOut` atténué. Par conséquent, l'animation commence et se termine avec le même effet. -## More interesting "draw" +## Un " draw " plus intéressant -Instead of moving the element we can do something else. All we need is to write the proper `draw`. +Au lieu de déplacer l'élément, nous pouvons faire autre chose. Il suffit d'écrire le bon `draw`. -Here's the animated "bouncing" text typing: +Voici la saisie animée du texte "rebondissant" : [codetabs src="https://github.com/text"] -## Summary +## Résumé -For animations that CSS can't handle well, or those that need tight control, JavaScript can help. JavaScript animations should be implemented via `requestAnimationFrame`. That built-in method allows to setup a callback function to run when the browser will be preparing a repaint. Usually that's very soon, but the exact time depends on the browser. +Pour les animations que CSS ne peut pas bien gérer, ou celles qui nécessitent un contrôle précis, JavaScript peut aider. Les animations JavaScript doivent être implémentées via `requestAnimationFrame`. Cette méthode intégrée permet de configurer une fonction callback à exécuter lorsque le navigateur prépare un repeint. En général, c'est très bientôt, mais le moment exact dépend du navigateur. -When a page is in the background, there are no repaints at all, so the callback won't run: the animation will be suspended and won't consume resources. That's great. +Lorsqu'une page est en arrière-plan, il n'y a pas de repeint du tout, donc la fonction de rappel ne sera pas exécutée : l'animation sera suspendue et ne consommera pas de ressources. C'est très bien. -Here's the helper `animate` function to setup most animations: +Voici la fonction d'aide `animate` pour configurer la plupart des animations : ```js function animate({timing, draw, duration}) { @@ -425,14 +425,14 @@ function animate({timing, draw, duration}) { let start = performance.now(); requestAnimationFrame(function animate(time) { - // timeFraction goes from 0 to 1 + // timeFraction passe de 0 à 1 let timeFraction = (time - start) / duration; if (timeFraction > 1) timeFraction = 1; - // calculate the current animation state + // calculer l'état courant de l'animation let progress = timing(timeFraction); - draw(progress); // draw it + draw(progress); // dessinez-le if (timeFraction < 1) { requestAnimationFrame(animate); @@ -442,14 +442,14 @@ function animate({timing, draw, duration}) { } ``` -Options: +Options : -- `duration` -- the total animation time in ms. -- `timing` -- the function to calculate animation progress. Gets a time fraction from 0 to 1, returns the animation progress, usually from 0 to 1. -- `draw` -- the function to draw the animation. +- `duration` -- la durée totale de l'animation en ms. +- `timing` -- la fonction pour calculer la progression de l'animation. Donne une fraction de temps de 0 à 1, retourne la progression de l'animation, généralement de 0 à 1. +- `draw` -- la fonction pour dessiner l'animation. -Surely we could improve it, add more bells and whistles, but JavaScript animations are not applied on a daily basis. They are used to do something interesting and non-standard. So you'd want to add the features that you need when you need them. +Nous pourrions certainement l'améliorer, mais les animations JavaScript ne sont pas utilisées quotidiennement. Elles sont utilisées pour faire quelque chose d'intéressant et de non standard. Vous voudriez donc ajouter les fonctionnalitées dont vous avez besoin quand vous en avez besoin. -JavaScript animations can use any timing function. We covered a lot of examples and transformations to make them even more versatile. Unlike CSS, we are not limited to Bezier curves here. +Les animations JavaScript peuvent utiliser n'importe quelle fonction de temporisation. Nous avons couvert beaucoup d'exemples et de transformations pour les rendre encore plus polyvalentes. Contrairement à CSS, nous ne sommes pas limités ici aux courbes de Bézier. -The same is about `draw`: we can animate anything, not just CSS properties. +Il en va de même pour `draw` : nous pouvons animer n'importe quoi, pas seulement des propriétés CSS.