Outils pour utilisateurs

Outils du site


issue150:inkscape

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
issue150:inkscape [2019/11/07 13:46] auntieeissue150:inkscape [2019/11/07 14:03] (Version actuelle) andre_domenech
Ligne 5: Ligne 5:
 Durant ces derniers mois, nous avons regardé les différentes façons de modifier dynamiquement votre contenu SVG quand il tourne dans un navigateur Web, en utilisant JavaScript. En faisant ces modifications sur un certain laps de temps, nous pouvons utiliser JS efficacement pour animer nos fichiers SVG. Durant ces derniers mois, nous avons regardé les différentes façons de modifier dynamiquement votre contenu SVG quand il tourne dans un navigateur Web, en utilisant JavaScript. En faisant ces modifications sur un certain laps de temps, nous pouvons utiliser JS efficacement pour animer nos fichiers SVG.
  
-Nous avons déjà une animation dans notre série : dans la partie 75, nous avons regardé des animations simples avec CSS, puis dans les parties 76 et 77, nous sommes passés à des animations avec SMIL. À ce moment-là, j'ai fait un commentaire pour indiquer que SMIL était une technologie en fin de vie, en grande partie parce que Microsoft ne l'avait jamais implémentée dans aucun navigateur. Mais les temps ont changé et Microsoft a réellement laissé tomber le développement de son propre moteur de navigation : dans peu de temps, Microsoft Edge commencera à utiliser le même moteur que Chrome, donnant par contre-coup un support à SMIL. Que ça suffise ou pas pour inverser les choses pour SMIL, reste à voir. Personnellement, je pense que c'est une superbe technologie, en particulier pour l'animation des SVG, mais les fournisseurs de navigateurs semblent considérer que les animations avec CSS sont la voie à suivre même si cette technologie ne couvre pas tous les cas d'utilisation que SMIL peut traiter.+Nous avons déjà une animation dans notre série : dans la partie 75, nous avons regardé des animations simples avec CSS, puis dans les parties 76 et 77, nous sommes passés à des animations avec SMIL. À ce moment-là, j'ai fait un commentaire pour indiquer que SMIL était une technologie en fin de vie, en grande partie parce que Microsoft ne l'avait jamais implémentée dans aucun navigateur. Mais les temps ont changé et Microsoft a réellement laissé tomber le développement de son propre moteur de navigation : dans peu de temps, Microsoft Edge commencera à utiliser le même moteur que Chrome, donnant par contre-coup un support à SMIL. Que ça suffise ou pas pour inverser les choses pour SMIL, reste à voir. Personnellement, je pense que c'est une superbe technologie, en particulier pour l'animation des SVG, mais les fournisseurs de navigateurs semblent considérer que les animations avec CSS sont la voie à suivremême si cette technologie ne couvre pas tous les cas d'utilisation que SMIL peut traiter.
  
 **So we’re slightly stuck in limbo. SMIL offers huge power, but its time may be short. CSS animation is less powerful, but widely supported. However with JavaScript we can sort-of get the best of both worlds: as much power and flexibility as we need, in a way that has excellent cross-browser support. **So we’re slightly stuck in limbo. SMIL offers huge power, but its time may be short. CSS animation is less powerful, but widely supported. However with JavaScript we can sort-of get the best of both worlds: as much power and flexibility as we need, in a way that has excellent cross-browser support.
Ligne 13: Ligne 13:
 Ainsi, nous sommes un peu dans le flou. SMIL offre une puissance énorme, mais son temps est sans doute compté. Les animations avec CSS sont moins puissantes, mais largement supportées. Cependant, avec JavaScript, nous pouvons avoir, en quelque sorte, le meilleur des deux mondes : autant de puissance et de flexibilité que nous voulons, avec le fait qu'il a un excellent support multi-navigateurs. Ainsi, nous sommes un peu dans le flou. SMIL offre une puissance énorme, mais son temps est sans doute compté. Les animations avec CSS sont moins puissantes, mais largement supportées. Cependant, avec JavaScript, nous pouvons avoir, en quelque sorte, le meilleur des deux mondes : autant de puissance et de flexibilité que nous voulons, avec le fait qu'il a un excellent support multi-navigateurs.
  
-Bien sûr, les choses ne sont pas toutes roses. Quand nous utilisons des animations avec SMIL ou CSS, nous privilégions une approche plutôt légère des choses. Votre saisie est une simple instruction : « Animer cet objet de A à B, en 5 secondes ». Vous n'avez pas besoin de dire comment la position de votre objet changera d'une trame à l'autre, ou de vous inquiéter de ce que votre animation impose une forte charge à la machine. Au lieu de ça, vous laissez le navigateur gérer tous les calculs intermédiaires et le code du navigateur est largement plus rapide pour gérer ces choses-là que tout ce que vous pourriez écrire en JavaScript.+Bien sûr, les choses ne sont pas toutes roses. Quand nous utilisons des animations avec SMIL ou CSS, nous privilégions une approche plutôt légère des choses. Votre saisie est une simple instruction : « Animer cet objet de A à B, en 5 secondes ». Vous n'avez pas besoin de dire comment la position de votre objet changera d'une trame à l'autre, ou de vous inquiéter de ce que votre animation impose une forte charge à la machine. Au lieu de ça, vous laissez le navigateur gérer tous les calculs intermédiaireset le code du navigateur est largement plus rapide pour gérer ces choses-là que tout ce que vous pourriez écrire en JavaScript.
  
 **So JS animation gives you flexibility, but at the expense of performance. Most of the time that won’t matter: the JavaScript engine in a modern browser is heavily optimised, so just moving an element or two around the screen isn’t likely to impose much of a burden. But if you start to animate a large number of objects, especially on a mobile device, you might find that your animations aren’t as smooth as they could be with the other technologies. **So JS animation gives you flexibility, but at the expense of performance. Most of the time that won’t matter: the JavaScript engine in a modern browser is heavily optimised, so just moving an element or two around the screen isn’t likely to impose much of a burden. But if you start to animate a large number of objects, especially on a mobile device, you might find that your animations aren’t as smooth as they could be with the other technologies.
Ligne 25: Ligne 25:
 **If you were to load that file into Inkscape, it should look like the image below. The page boundary is a square of 100×100 units, as defined in the viewBox attribute. The square itself is positioned with its top left corner at 10 units down, and 10 units across from the origin (the top-left of the page in SVG). Remember these units are not pixels – the image will actually be scaled to fit the available space in the browser window. By using a 100×100 viewBox it can be convenient to think of the values as percentages, but in reality it’s better to treat them as proportions or ratios, as that mental model works regardless of the viewBox size.** **If you were to load that file into Inkscape, it should look like the image below. The page boundary is a square of 100×100 units, as defined in the viewBox attribute. The square itself is positioned with its top left corner at 10 units down, and 10 units across from the origin (the top-left of the page in SVG). Remember these units are not pixels – the image will actually be scaled to fit the available space in the browser window. By using a 100×100 viewBox it can be convenient to think of the values as percentages, but in reality it’s better to treat them as proportions or ratios, as that mental model works regardless of the viewBox size.**
  
-Si vous chargiez ce fichier dans Inkscape, il ressemblerait à l'image du haut de la page suivante. Les limites de la page sont un carré de 100x100 unités, comme défini dans l'attribut de viewBox. Le carré lui-même est positionné avec son angle du haut à gauche à 10 unités sous, et 10 unités à droite, de l'origine (l'angle en haut à gauche dans SVG). Souvenez-vous que ces unités ne sont pas des pixels l'image sera en fait redimensionnée pour s'adapter à la place disponible dans la fenêtre du navigateur. En utilisant une viewBox de 100x100, il est pratique de voir ces dimensions comme des pourcentages, mais, en fait, c'est mieux de les traiter comme des proportions ou des rapports, car ce modèle mental fonctionne quelle que soit la taille de la viewBox.+Si vous chargiez ce fichier dans Inkscape, il ressemblerait à l'image du haut de la page suivante. Les limites de la page sont un carré de 100x100 unités, comme défini dans l'attribut de viewBox. Le carré lui-même est positionné avec son angle du haut à gauche à 10 unités sous, et 10 unités à droite, de l'origine (l'angle en haut à gauche dans SVG). Souvenez-vous que ces unités ne sont pas des pixelsl'image sera en fait redimensionnée pour s'adapter à la place disponible dans la fenêtre du navigateur. En utilisant une viewBox de 100x100, il est pratique de voir ces dimensions comme des pourcentages, mais, en fait, c'est mieux de les traiter comme des proportions ou des rapports, car ce modèle mental fonctionne quelle que soit la taille de la viewBox.
  
 **We’re going to animate the “x” attribute from its starting value of 10 up to a value of 90. Because the square is 30 units wide, this will leave it hanging off the right-hand side of the screen when the animation finishes. I’ve done this to demonstrate a key difference between animating the content of an SVG file, and animating a <div> or other box in an HTML page: in the latter case the page width will grow and a horizontal scroll bar will appear (unless you specifically prevent that behaviour). With an SVG file, anything outside the viewBox simply isn’t rendered, making it easier to have animations that start or end ‘off-screen’. Think of it a little like a theatre stage, with your props and characters moving to and from the wings.** **We’re going to animate the “x” attribute from its starting value of 10 up to a value of 90. Because the square is 30 units wide, this will leave it hanging off the right-hand side of the screen when the animation finishes. I’ve done this to demonstrate a key difference between animating the content of an SVG file, and animating a <div> or other box in an HTML page: in the latter case the page width will grow and a horizontal scroll bar will appear (unless you specifically prevent that behaviour). With an SVG file, anything outside the viewBox simply isn’t rendered, making it easier to have animations that start or end ‘off-screen’. Think of it a little like a theatre stage, with your props and characters moving to and from the wings.**
Ligne 78: Ligne 78:
 clearInterval(i);** clearInterval(i);**
  
-Bon. Je ne pense pas que ça inquiète beaucoup Pixar, mais il est bel et bien animé. La création d'une longue liste d'appels setTimeout() n'est vraiment pas génial. Par chance, JavaScript a une fonction adaptée, setInterval(), qui fait la même chose qu'une liste infinie d'appels setTimeout(). Elle retourne un seul nombre qui peut être utilisé avec la méthode clearInterval() pour arrêter le traitement quand vous en avez marre de voir bouger ce carré par saccades.+Bon. Je ne pense pas que ça inquiète beaucoup Pixar, mais il est bel et bien animé. La création d'une longue liste d'appels setTimeout() n'est vraiment pas géniale. Par chance, JavaScript a une fonction adaptée, setInterval(), qui fait la même chose qu'une liste infinie d'appels setTimeout(). Elle retourne un seul nombre qui peut être utilisé avec la méthode clearInterval() pour arrêter le traitement quand vous en avez marre de voir bouger ce carré par saccades.
  
 var i = setInterval(moveSquare, 100); var i = setInterval(moveSquare, 100);
  
-<nowiki> // Un peu plus tard</nowiki>+<nowiki> // Un peu plus tard...</nowiki>
 clearInterval(i); clearInterval(i);
  
Ligne 100: Ligne 100:
 var i = setInterval(moveSquare, 10); var i = setInterval(moveSquare, 10);
  
-<nowiki> // Un peu plus tard</nowiki>+<nowiki> // Un peu plus tard...</nowiki>
 clearInterval(i); clearInterval(i);
  
-Est-ce encore un peu rapide pour vous ? Augmentez le délai dans l'appel de setInterval(). Pas encore assez rapide ? Vous pouvez réduire encore le délai, mais les navigateurs bloquent setTimeout() et setInterval() à une limite basse ; aussi, ça n'aura pas beaucoup d'effet. À la place, vous pouvez augmenter la valeur de delta de sorte que le carré se déplace de 2 ou 3 unités à chaque fois. Ou de 4,25, si vous voulez Ni JS ni SVG n'imposent que les valeurs soient des entiers.+Est-ce encore un peu rapide pour vous ? Augmentez le délai dans l'appel de setInterval(). Pas encore assez rapide ? Vous pouvez réduire encore le délai, mais les navigateurs bloquent setTimeout() et setInterval() à une limite basse ; aussi, ça n'aura pas beaucoup d'effet. À la place, vous pouvez augmenter la valeur de delta de sorte que le carré se déplace de 2 ou 3 unités à chaque fois. Ou de 4,25, si vous voulezNi JS ni SVG n'imposent que les valeurs soient des entiers.
  
 **For a long time setTimeout() and setInterval() were the only practical way to run some JavaScript at the sort of regular intervals needed for animation. Over the past few years, however, browsers have gained more support for technologies needed to run games – 2D bitmap canvases, 3D graphics and a little thing called requestAnimationFrame(). In case the name didn’t give it away, this function is intended to make animation a little easier. Specifically it does so by calling a function just before the browser is about to display the next frame on screen (typically about 60 times per second). It’s like a setTimeout() where the delay is automatically set to to an optimal value by the browser.** **For a long time setTimeout() and setInterval() were the only practical way to run some JavaScript at the sort of regular intervals needed for animation. Over the past few years, however, browsers have gained more support for technologies needed to run games – 2D bitmap canvases, 3D graphics and a little thing called requestAnimationFrame(). In case the name didn’t give it away, this function is intended to make animation a little easier. Specifically it does so by calling a function just before the browser is about to display the next frame on screen (typically about 60 times per second). It’s like a setTimeout() where the delay is automatically set to to an optimal value by the browser.**
  
-Pendant longtemps, setTimeout() et setInterval() furent la seule façon pratique de lancer du JavaScript aux intervalles réguliers nécessaires à une animation. Dans les dernières années, cependant, les navigateurs ont disposé d'un support pour les technologies nécessaires pour faire tourner des jeux canevas 2D en bitmap, affichage 3D et une petite chose appelée requestAnimationFrame(). Au cas où le nom ne vous dit rien, cette fonction a tendance à faciliter la réalisation d'une animation. En particulier, elle le fait en appelant une fonction juste avant que le navigateur ne se mette à afficher la trame suivante sur l'écran (en général, 60 fois par seconde). Elle ressemble à setTimeout(), avec un délai mis automatiquement à la valeur optimale par le navigateur.+Pendant longtemps, setTimeout() et setInterval() furent la seule façon pratique de lancer du JavaScript aux intervalles réguliers nécessaires à une animation. Dans les dernières années, cependant, les navigateurs ont disposé d'un support pour les technologies nécessaires pour faire tourner des jeux canevas 2D en bitmap, affichage 3D et une petite chose appelée requestAnimationFrame(). Au cas où le nom ne vous dit rien, cette fonction a tendance à faciliter la réalisation d'une animation. En particulier, elle le fait en appelant une fonction juste avant que le navigateur ne se mette à afficher la trame suivante sur l'écran (en général, 60 fois par seconde). Elle ressemble à setTimeout(), avec un délai mis automatiquement à la valeur optimale par le navigateur.
  
 **In human terms 1/60 of a second is a pretty short delay, so to test this in the console you will probably want to increate the “delta” variable again, so that it’s more obvious that your square moves. **In human terms 1/60 of a second is a pretty short delay, so to test this in the console you will probably want to increate the “delta” variable again, so that it’s more obvious that your square moves.
Ligne 117: Ligne 117:
 Now you might be expecting me to introduce an equivalent animation function to setInterval(), but I’m afraid I’ll have to disappoint you. There’s no function that will repeatedly run a function just before each frame is redrawn. But what we can do is to call requestAnimationFrame() again from inside the animation function.** Now you might be expecting me to introduce an equivalent animation function to setInterval(), but I’m afraid I’ll have to disappoint you. There’s no function that will repeatedly run a function just before each frame is redrawn. But what we can do is to call requestAnimationFrame() again from inside the animation function.**
  
-À l'échelle humaine, 1/60e de seconde est un temps plutôt court ; aussi, pour le tester sur la console vous voudrez peut-être encore augmenter la variable « delta », de sorte que le déplacement du carré est plus évident.+À l'échelle humaine, 1/60e de seconde est un temps plutôt court ; aussi, pour le tester sur la console vous voudrez peut-être encore augmenter la variable « delta », de sorte que le déplacement du carré soit plus évident.
  
 var delta = 10; var delta = 10;
Ligne 123: Ligne 123:
 requestAnimationFrame(moveSquare); requestAnimationFrame(moveSquare);
  
-Maintenant, vous attendez peut-être de moi que je vous présente une fonction d'animation équivalente à setInterval(), mais, à mon grand regret, je vais vous décevoir. Il n'y a pas de fonction qui lance de façon répétée une fonction juste avant que chaque trame soit redessinée. Maisce que nous pouvons faire est de rappeler requestAnimationFrame() depuis l'intérieur de la fonction d'animation.+Maintenant, vous attendez peut-être de moi que je vous présente une fonction d'animation équivalente à setInterval(), mais, à mon grand regret, je vais vous décevoir. Il n'y a pas de fonction qui lance de façon répétée une fonction juste avant que chaque trame soit redessinée. Mais ce que nous pouvons faire est de rappeler requestAnimationFrame() depuis l'intérieur de la fonction d'animation.
  
 **We’ll create a different animation function (shown above) for this next example. It’s similar to the previous one, except that it always moves the square by 1 unit, and stops when it reaches the right-hand side, rather than looping back round. This latter change is mainly so that the code doesn’t keep running indefinitely, otherwise it gets a bit tricky to proceed with the rest of this tutorial. Notice that we call requestAnimationFrame() to start the function running, but we also call this from within the “if” block, firing off another trip to our animation function just before the next frame is rendered.** **We’ll create a different animation function (shown above) for this next example. It’s similar to the previous one, except that it always moves the square by 1 unit, and stops when it reaches the right-hand side, rather than looping back round. This latter change is mainly so that the code doesn’t keep running indefinitely, otherwise it gets a bit tricky to proceed with the rest of this tutorial. Notice that we call requestAnimationFrame() to start the function running, but we also call this from within the “if” block, firing off another trip to our animation function just before the next frame is rendered.**
  
-Nous créerons une fonction d'animation différente (voir ci-dessus) pour ce nouvel exemple. Il est semblable au précédent, sauf que le carré se déplace toujours d'une unité et qu'il s'arrête quand il atteint le côté droit, plutôt que de tourner en rond pour le retour. Ce dernier changement est fait de telle sorte que le code ne continue pas à s'exécuter indéfiniment autrement, ce serait un peu compliqué pour réaliser le reste de ce tutoriel. Notez que nous appelons requestAnimationFrame() pour commencer le lancement de la fonction, mais nous l'appelons aussi à l'intérieur du bloc « if », déclenchant un nouveau parcours pour notre fonction d'animation juste avant que le rendu de la trame suivante ne soit affiché.+Nous créerons une fonction d'animation différente (voir ci-dessus) pour ce nouvel exemple. Il est semblable au précédent, sauf que le carré se déplace toujours d'une unité et qu'il s'arrête quand il atteint le côté droit, plutôt que de tourner en rond pour le retour. Ce dernier changement est fait de telle sorte que le code ne continue pas à s'exécuter indéfinimentautrement, ce serait un peu compliqué pour réaliser le reste de ce tutoriel. Notez que nous appelons requestAnimationFrame() pour commencer le lancement de la fonction, mais nous l'appelons aussi à l'intérieur du bloc « if », déclenchant un nouveau parcours pour notre fonction d'animation juste avant que le rendu de la trame suivante ne soit affiché.
  
 **Now we’ve got an animation running, but we don’t really have any control over it. The duration of the animation will depend on how frequently requestAnimationFrame() fires in your browser, and all we can do is change “+ 1” to a different value to make the square move more or less on each iteration. But really that’s all we need to be able to do. So long as we know the exact time that the function is called, we can calculate how far into the animation we are, and therefore what position the square should be at. To achieve this, the function that is called by getAnimationFrame() receives a single parameter: a high-resolution timestamp.** **Now we’ve got an animation running, but we don’t really have any control over it. The duration of the animation will depend on how frequently requestAnimationFrame() fires in your browser, and all we can do is change “+ 1” to a different value to make the square move more or less on each iteration. But really that’s all we need to be able to do. So long as we know the exact time that the function is called, we can calculate how far into the animation we are, and therefore what position the square should be at. To achieve this, the function that is called by getAnimationFrame() receives a single parameter: a high-resolution timestamp.**
  
-Maintenant, notre animation tourne, mais nous n'avons vraiment aucun contrôle sur elle. La durée de l'animation dépendra du nombre de fois où requestAnimationFrame() se déclenchera dans votre navigateur et tout ce que nous pouvons faire est de changer « +1 » pour une autre valeur pour que le carré bouge plus ou moins rapidement à chaque itération.  Mais vraiment, c'est tout ce que nous sommes capables de faire. Tant que nous connaissons le moment exact où la fonction est appelée, nous pouvons calculer le temps déjà pris par l'animation, et par conséquent, où devrait en être le carré. Pour faire cela, la fonction qui est appelée par getAnimationFrame() reçoit un seul paramètre : une horodatage en haute-résolution.+Maintenant, notre animation tourne, mais nous n'avons vraiment aucun contrôle sur elle. La durée de l'animation dépendra du nombre de fois où requestAnimationFrame() se déclenchera dans votre navigateur et tout ce que nous pouvons faire est de changer « +1 » pour une autre valeur pour que le carré bouge plus ou moins rapidement à chaque itération.  Mais vraiment, c'est tout ce que nous sommes capables de faire. Tant que nous connaissons le moment exact où la fonction est appelée, nous pouvons calculer le temps déjà pris par l'animation, et par conséquent, où devrait en être le carré. Pour faire cela, la fonction qui est appelée par getAnimationFrame() reçoit un seul paramètre : un horodatage en haute résolution.
  
 **Let’s work on a practical example: suppose we want our animation to take 10 seconds. At 60 frames per second that’s about 600 movements our square will make, each of them a fraction of a unit. We could divide the total distance by 600 to calculate the exact amount of movement, but that will fail if we run the code on something that refreshes at 30 or 120 frames per second, or if some frames get dropped due to the load on the machine. A better idea is to track how long has passed since the start of the animation, and use that to calculate where the object should be. We can then set the coordinates to the new value, before we fire off another requestAnimationFrame() for the next step in the animation.** **Let’s work on a practical example: suppose we want our animation to take 10 seconds. At 60 frames per second that’s about 600 movements our square will make, each of them a fraction of a unit. We could divide the total distance by 600 to calculate the exact amount of movement, but that will fail if we run the code on something that refreshes at 30 or 120 frames per second, or if some frames get dropped due to the load on the machine. A better idea is to track how long has passed since the start of the animation, and use that to calculate where the object should be. We can then set the coordinates to the new value, before we fire off another requestAnimationFrame() for the next step in the animation.**
Ligne 139: Ligne 139:
 **The parameter that gets passed to our function is a value in milliseconds since the document was loaded. We don’t really care about that specific point in time – we need to know how long the animation itself has been running. What we need to do, therefore, is to record the timestamp the first time our function is called. On subsequent calls we can subtract that value from the latest timestamp to work out how far along the animation timeline we have progressed.** **The parameter that gets passed to our function is a value in milliseconds since the document was loaded. We don’t really care about that specific point in time – we need to know how long the animation itself has been running. What we need to do, therefore, is to record the timestamp the first time our function is called. On subsequent calls we can subtract that value from the latest timestamp to work out how far along the animation timeline we have progressed.**
  
-Le paramètre qui a été passé à notre fonction quand le document a été chargé est une valeur en millisecondes. Nous ne nous soucions vraiment pas de ce moment spécifique nous avons besoin de savoir depuis combien de temps l'animation tourne. Par conséquent, ce que nous avons à faire, c'est d'enregistrer l'hotodatage lors du premier appel de la fonction.  Lors des appels suivants, nous pouvons soustraire cette valeur du plus récent horodatage pour calculer de combien nous avons progressé sur la durée de l'animation.+Le paramètre qui a été passé à notre fonction quand le document a été chargé est une valeur en millisecondes. Nous ne nous soucions vraiment pas de ce moment spécifiquenous avons besoin de savoir depuis combien de temps l'animation tourne. Par conséquent, ce que nous avons à faire, c'est d'enregistrer l'hotodatage lors du premier appel de la fonction.  Lors des appels suivants, nous pouvons soustraire cette valeur du plus récent horodatage pour calculer de combien nous avons progressé sur la durée de l'animation.
  
 **Let’s start by initialising a few variables. We’ll create a variable to hold our starting position, setting it to 10. Next we have a “duration” (in milliseconds) to hold the time we want our animation to run for, and “endX” for the X coordinate we want to end up with. Putting these into variables makes it easier to modify the animation to run at a different speed or cover a different distance. Finally we’ll include a “startTime” variable, with an “undefined” value initially, into which we’ll store a copy of the timestamp we receive the first time our animation code is called. **Let’s start by initialising a few variables. We’ll create a variable to hold our starting position, setting it to 10. Next we have a “duration” (in milliseconds) to hold the time we want our animation to run for, and “endX” for the X coordinate we want to end up with. Putting these into variables makes it easier to modify the animation to run at a different speed or cover a different distance. Finally we’ll include a “startTime” variable, with an “undefined” value initially, into which we’ll store a copy of the timestamp we receive the first time our animation code is called.
Ligne 159: Ligne 159:
 **Now for our reworked animation function. The main animation code is fairly similar to the previous incarnation, except that we work with the timestamp that is passed to the function in order to calculate the new X value. The first time the function is called we don’t need to update the X coordinate – by definition we’re at the start of the animation – so we just store the current timestamp, then queue up another call before the next frame, then exit. On subsequent calls, the startTime is no longer “undefined” so this part of the function is skipped entirely.** **Now for our reworked animation function. The main animation code is fairly similar to the previous incarnation, except that we work with the timestamp that is passed to the function in order to calculate the new X value. The first time the function is called we don’t need to update the X coordinate – by definition we’re at the start of the animation – so we just store the current timestamp, then queue up another call before the next frame, then exit. On subsequent calls, the startTime is no longer “undefined” so this part of the function is skipped entirely.**
  
-Pour ce qui est de notre fonction d'animation retravaillée, le principal code de l'animation est très similaire à la précédente version, sauf que nous travaillons avec l'horodatage qui est passé à la fonction de façon à calculer la nouvelle valeur de X. La première fois que la fonction est appelée, nous n'avons pas besoin de mettre à jour la coordonnée X - par définition, nous sommes au début de l'animation - aussi, nous ne faisons qu'enregistrer l'horodatage actuel. Puis, un autre appel suit avant la prochaine trame, et nous sortons. Lors des appels suivants, startTime n'est plus indéfini, et cette partie de la fonction est sautée complètement.+Pour ce qui est de notre fonction d'animation retravaillée, le principal code de l'animation est très similaire à la précédente version, sauf que nous travaillons avec l'horodatage qui est passé à la fonction de façon à calculer la nouvelle valeur de X. La première fois que la fonction est appelée, nous n'avons pas besoin de mettre à jour la coordonnée X - par définition, nous sommes au début de l'animation - aussi, nous ne faisons qu'enregistrer l'horodatage actuel. Puis, un autre appel suit avant la prochaine trame, et nous sortons. Lors des appels suivants, startTime n'est plus indéfini, et cette partie de la fonction est sautée complètement.
  
 **By storing the initial timestamp outside the function, we can calculate how long the animation has been running. Since the two timestamps are in milliseconds, we’ll divide the result by 1000 to convert it to seconds. Since we know the total time for the animation, a quick division will give the proportion of the animation that has passed: we can then multiply that value by the total distance to travel in order to calculate the new X position for that moment in time. Code is shown below.** **By storing the initial timestamp outside the function, we can calculate how long the animation has been running. Since the two timestamps are in milliseconds, we’ll divide the result by 1000 to convert it to seconds. Since we know the total time for the animation, a quick division will give the proportion of the animation that has passed: we can then multiply that value by the total distance to travel in order to calculate the new X position for that moment in time. Code is shown below.**
  
-En enregistrant l'horodatage initial hors de la fonction, nous pouvons calculer depuis combien de temps l'animation tourne. Comme les deux horodatages sont en millisecondes, nous diviserons le résultat par 1000 pour le convertir en secondes. Comme nous connaissons le temps total de l'animation, une rapide division nous donnera le part de l'animation déjà passée : nous pouvons ensuite multiplier cette valeur par la distance totale du déplacement pour calculer la nouvelle position X à cet instant. Le code est présenté ci-dessous.+En enregistrant l'horodatage initial hors de la fonction, nous pouvons calculer depuis combien de temps l'animation tourne. Comme les deux horodatages sont en millisecondes, nous diviserons le résultat par 1 000 pour le convertir en secondes. Comme nous connaissons le temps total de l'animation, une rapide division nous donnera la part de l'animation déjà passée : nous pouvons ensuite multiplier cette valeur par la distance totale du déplacement pour calculer la nouvelle position X à cet instant. Le code est présenté ci-dessous.
  
 **Running this should produce a smooth animation that takes 10s to complete. Re-run the previous block of “var” lines to reset everything, then the final requestAnimationFrame() call to kick it off again. Try changing the values in the variables to alter the distance the square moves, or the time it takes to perform the animation. In every case you should find that the animation is, if not smooth, at least a lot smoother than you saw with setTimeout() and setInterval().** **Running this should produce a smooth animation that takes 10s to complete. Re-run the previous block of “var” lines to reset everything, then the final requestAnimationFrame() call to kick it off again. Try changing the values in the variables to alter the distance the square moves, or the time it takes to perform the animation. In every case you should find that the animation is, if not smooth, at least a lot smoother than you saw with setTimeout() and setInterval().**
  
-Une fois lancé, il produira une animation fluide qui prendra 10 s en tout. Relancez le bloc précédent des lignes « var » pour tout remettre à zéro, puis finissez avec un dernier appel requestAnimationFrame() pour redémarrer. Essayez de changer les valeurs des variables pour modifier la distance de déplacement du carré, ou le temps pris pour dérouler l'animation. Dans chaque cas, vous devriez trouver que l'animation est, sinon fluide, au moins plus fluide que celle que vous vîtes avec setTimeout() et setInterval().+Une fois lancé, il produira une animation fluide qui prendra 10 sen tout. Relancez le bloc précédent des lignes « var » pour tout remettre à zéro, puis finissez avec un dernier appel requestAnimationFrame() pour redémarrer. Essayez de changer les valeurs des variables pour modifier la distance de déplacement du carré, ou le temps pris pour dérouler l'animation. Dans chaque cas, vous devriez trouver que l'animation est, sinon fluide, au moins plus fluide que celle que vous avez vue avec setTimeout() et setInterval().
  
 **Creating all these variables outside a function (so-called “global” variables) is generally seen as bad form in the programming world. It also makes it tricky to animate more than one thing, as they’ll all potentially be sharing the same global variables. A better approach is to encapsulate all the variables in a single JavaScript object, then attach that to the SVG element you’re trying to manipulate. Here’s the code above rewritten to work in this way (shown right).** **Creating all these variables outside a function (so-called “global” variables) is generally seen as bad form in the programming world. It also makes it tricky to animate more than one thing, as they’ll all potentially be sharing the same global variables. A better approach is to encapsulate all the variables in a single JavaScript object, then attach that to the SVG element you’re trying to manipulate. Here’s the code above rewritten to work in this way (shown right).**
  
-La création de toutes ces variables en dehors d'une fonction (appelées variables « globales ») est généralement vu comme une mauvaise pratique dans le monde de la programmation. Cela rend difficile l'animation de plus d'un objet, car ils se partagent tous théoriquement les mêmes variables globales. Une meilleure approche consiste à encapsuler toutes les variables dans un seul ojet JavaScript, puis de l'attacher à l'élément SVG que vous essayez de manipuler. Voici, à droite, le code réécrit de cette façon.+La création de toutes ces variables en dehors d'une fonction (appelées variables « globales ») est généralement vu comme une mauvaise pratique dans le monde de la programmation. Cela rend difficile l'animation de plus d'un objet, car ils se partagent tous théoriquement les mêmes variables globales. Une meilleure approche consiste à encapsuler toutes les variables dans un seul objet JavaScript, puis de l'attacher à l'élément SVG que vous essayez de manipuler. Voici, à droite, le code réécrit de cette façon.
  
 **Notice that I’ve removed the “X” from the end of the parameter names, and created a new “attribute” entry with a value of “x”. This starts to make the code more generic: you could change the “x” to a “y” in order to animate movement in the vertical direction, or “r” to animate the radius of a circle. **Notice that I’ve removed the “X” from the end of the parameter names, and created a new “attribute” entry with a value of “x”. This starts to make the code more generic: you could change the “x” to a “y” in order to animate movement in the vertical direction, or “r” to animate the radius of a circle.
issue150/inkscape.txt · Dernière modification : 2019/11/07 14:03 de andre_domenech