Outils pour utilisateurs

Outils du site


issue136:inkscape

Ceci est une ancienne révision du document !


Last time, we looked at how it’s possible to include animations in an SVG file that is loaded as an image. We introduced the general idea by animating the fill and stroke colors, and the stroke width, of a square we’d drawn in Inkscape. If we’re just working with a square – or even a rounded rectangle – we could equally achieve the same effect in HTML by animating the “background” and “border” CSS properties, with no need to go near SVG. But the important point to note is that we actually used CSS to animate properties that only make sense for SVG. In other words, although CSS is most commonly used with HTML, we can still use it to modify many SVG-only values. Furthermore, we can animate those properties not only on squares and rectangles, but also on arbitrary paths. By reusing the same animation that we had in the previous article, we can produce the same set of three snapshots, but this time of a more complex shape. For this example I created a star in Inkscape and converted it to a path. The first CSS rule, which previously had a selector of “rect”, also needed to be updated to change the selector to “path”.

La dernière fois, nous avons regardé comment il était possible d’inclure des animations dans un fichier SVG qi est chargé dans une image. Nous avons présenté l’idée générale en animant les couleurs de remplissage et de contour, et la largeur du trait, d’un carré que j’avais dessiné dans Inkscape. Si vous n’avez travaillé que sur un carré - ou même sur un rectangle arrondi - vous pouvez obtenir le même effet en HTML en animant les propriétés « background » (arrière-plan) et « border » (bordure) du CSS, sans avoir besoin de s’approcher de SVG. Mais le point important à noter est que nous avons utilisé réellement le CSS pour animer des propriétés qui n’ont de sens qu’en SVG. En d’autres termes, bien que le CSS est utilisé plus communément que le HTML, nous pouvons toujours l’utiliser pour modifier des nombreuses valeurs propres à SVG. Par conséquent, nous pouvons animer ces propriétés, non seulemnt pour les carrés et les rectangles, pais aussi pour des chemins arbitraires.

En réutilisant la même animation que celle de l’article précédent, nous pouvons produire le même jeu de trois instantanés, mais cette fois sur une forme plus complexe. Pour cet exemple, j’ai créé un étoile dans Inkscape, convertie ensuite en chemin. La première règle du CSS, qui avait précédemment un sélecteur de « rect », avait aussi besoin d’être mise à jour pour changer le sélecteur vers « path ».

But what if you want to animate more than just the style of your elements? Perhaps you want to make them move around, to spin, or to change size. You might even want the shape of the path itself to change. All this and more is possible with SVG… but, as will become clear, I don’t necessarily recommend doing it. As I’ve previously discussed in this column, there was a time when the W3C went full tilt in favor of XML. They defined and specified a wide range of XML languages – including SVG and XHTML (a pure XML version of HTML) – as well as working on various supporting technologies that could work with any XML language. One of these technologies was the “Synchronized Multimedia Integration Language”, or SMIL (pronounced “smile” apparently). SMIL is itself an XML language that describes how an XML document should change over time, or in response to certain interactions such as mouse movements and clicks. In the case of SVG, therefore, SMIL can be used to describe the way in which arbitrary attributes should change over time, allowing any part of the image to be animated.

Mais que se passe-t-il si vous voulez aimer plus que le seul style de vos éléments ? Peut-être que vous voulez les faire bouger, tourner et changer de taile. Vous pourriez même vouloir que la forme du chemin lui-même change. Tout ceci et et plus est possible avec SVG… mais, comme cela deviendra clair, je ne vous recommande pas nécessairement de la faire.

Comme je l’ai déjà présenté précédemment dans cet article, il y a eu un temps où le W3C était à fond pour le XML. Ils ont défini et spécifié un large éventail de langages XML - y compris SVG et XHTML ( une version pure XML du HTML) - tout en travaillant aussi des technologies de support qui pourraient fonctionner avec n’importe quel langage XML. Une de ces technologies était le « Synchronized Multimedia Integration Language » (Langage d’intégration du multimédia synchronisé) ou SMIL (prononcez « smile » (sourire) apparemment). SMIL est lui-même un langage XML qui décrit comment un document XML doit changer dans le temps ou en réponse à certaines interactions comme les mouvements de souris ou les clics. Dans le cas du SVG, par conséquent, SMIL peut être utilisé pour décrire la manière de changer dans le temps pour des attributs arbitraires, permettant d’animer n’importe quelle partie de l’image.

If the W3C’s plan for XML domination had panned out, SMIL would probably have become a universally implemented technology for animation and multimedia. In practice, however, browsers veered away from the XML-centric approach in favor of the more lax requirements of HTML, and Microsoft never implemented SMIL in their browsers. Faced with an animation standard that wasn’t supported by Internet Explorer, it’s no wonder that so much early animation on the web was outsourced to Flash. The result was that SVG languished for a long time and SMIL never really took off. In the meantime, CSS gained more and more abilities that were once the remit of SVG, and has begun to encroach on the domain of SMIL with CSS animations and transitions. The penultimate nail in the SMIL coffin came with the release of version 45 of Google’s Chrome browser, which officially listed the technology as deprecated. It would still work for the time being, but that was notification that it’s eventually going away. After a backlash from the community they revoked this announcement, so SMIL is no longer deprecated in Chrome – but it’s only a matter of time before they decide that CSS animations are capable enough for them to try again. So that’s why I don’t really recommend using SMIL: with no support in Internet Explorer or Edge, and the prospect of being deprecated then removed in Chrome at some indeterminate point, it’s not a technology that can be relied on as a viable solution for use on the web at large.

Si les plans du W3C pour une domination du XML avait réussi, SMIL serait probablement devenue une technologie universellement implémentée pour l’animation et le multimédia. En pratique, cependant, les navigateurs se sont éloignés d’un approche centrée sur le XML en faveur des exigences plus laxistes du HTML, et Microsoft n’a jamais implémenté SMIL dans ses navigateurs. Face à une norme d’animation qui n’était pas supportée pat Internet Explorer, ce n’est pas une surprise que tant d’animations au début aient été basées sur Flash. Le résultat a été que le SVG a stagné pendant longtemps et et que SMIL n’avait vraiment décollé. Entre temps, le CSS a gagné de plus en plus de capacités qui avaient été autrefois dans les attributions du SVG, et a commencé à empiéter sur le domaine de SMIL avec les animations et les transitions du CSS.

L’avant-dernier clou dans le cercueil de SMIL est venu de la publication 45 du navigateur Chrome de Google, qui a officiellement listé cette technologie comme obsolète. Il fonctionnerait encore à l’heure actuelle, mais c’était l’annonce qu’il partait finalement. Après une réaction défavorable de la communauté, l’annonce fut révoquée, de sorte que SMIL n’est plus obsolète dans Chrome - mais ce n’est qu’une question de temps avant qu’ils décident que les animations du CSS ont suffisamment de capacités pour qu’ils réessayent. Aussi, c’est pour cela que je ne cvous recommande pas d’utiliser SMIL : sans aucun support dans Internet Explorer ou Edge, et avec la perspective d’être déprécié puis supprimé de Chrome à un moment indéterminé, ce n’est pas une technologie sur laquelle s’appuyer comme solution viable pour un usage étendu sur le Web.

Given this situation I’m not going to discuss SMIL in any great detail. But as it is (currently) usable in (most) web browsers, I’ll spend a couple of articles giving you a brief introduction in case you feel it is a technology that you can use and wish to investigate further – and as an insight into the sort of web we might have now, had Microsoft played ball, and XML gained stronger support from the browser vendors. There are four types of animation that can be performed using SMIL with SVG, in each case by adding the relevant animation tag (shown in brackets) inside the element you want to animate: • Animate the attributes of an SVG element • Animate the transformation that can be applied to an SVG element (<animateTransform>). • Animate the color of the fill and stroke (<animate> or <animateColor>). • Animate the position and, optionally, rotation of an object by making it follow another path (<animateMotion>).

Étant donné la situation, je ne vais pas présenté SMIL en détail. Mais, comme il est utilisable (actuellement) dans (la plupart) des navigateurs Web, je vous en donnerai une courte introduction dans quelques articles, au cas où vous sentez que c’est une technologie que vous pouvez utiliser et que vous souhaitez l’examiner plus en détail - - et comme un aperçu de la sorte de Web que vous pourriez avoir maintenant, si Microsoft avait joué le jeu et que XML ait reçu un support plus appuyé de la part des fournisseurs de navigateurs.

Il y a quatre types d’animations qui peuvent être réalisés en utilisant SMIL avec SVG, en ajoutant, dans chaque cas, la balise d’animation correcte (montrée entre parenthèses) dans l’élément que vous voulez animer :

• Animer les attributs de l ‘élément SVG (<animate>).

• Animer la transformation qui peut être appliquée à un élément SVG (<animateTransform>).

• Animer les couleurs de remplissage et contour (<animate> ou <animateColor>).

• Animer la position et , optionnellement, la rotation d’un objet en lui faisant suivre un autre chemin (<animateMotion>).

Let’s look at a simple example, by trying to replicate the CSS animation of the same red star I used earlier. In this case we will need to animate the fill and stroke color, and the stroke width, using the <animate> tag. So rather than having those values stored as CSS properties, they need to be moved out to independent attributes. This results in our SVG file looking something like that shown top right. Note that, for simplicity, I’ve rounded all the coordinates down to whole numbers. There’s also a transform attribute that translates the star 20 units to the right, and 20 units down: I could have done the calculations to adjust the coordinates for the path, removing the need for this entirely. As Inkscape seems rather keen to put transforms onto its content, however, I decided to leave it in to better represent the sort of (minimised) output you might see from the program.

Regardons un simple exemple, en essayant de reproduire l’animation CSS de la même étaoile rouge que j’ai utilisée plus tôt. Dans ce cas-ci, nous aurons à animer les couleurs de remplissage et de contour, ainsi que la largeur du trait, en utilisant la balise <animate>. Plutôt que d’avoir ces valeurs stockées dans les propriétés du CSS, elles devront être ressorties comme des attributs indépendants. Ceci fait ressembler notre fichier SVG à quelque chose comme ce qui est montré en haut à droite.

Notez que, pour la simplicité, j’ai arrondi toutes les coordonnées à l’entier en-dessous. Il y a aussi un attribut de transformation qui déplace l’étoile de 20 unités vers la droite, et 20 vers le bas : j’aurai pu fiare des calculs pour ajuster les coordonnées au chemin, supprimant entièrement le besoin de celui-ci. Cependant, comme Inkscape semble plutôt intelligent pour mettre les transformation sur son contenu, j’ai décidé de le laisser dedans pour mieux représenter la sorte de sortie (minimisée) du programme que vous pouvez voir.

As with the CSS animations from last time, I’m going to start by just animating the fill color. This involves putting the <animate> tag as a child element of the <path>. In case you’re not very familiar with XML, in the previous code the path is written as a self-closing tag: This can legitimately be rewritten as a non-self-closing tag: <path …></path>. It’s this latter approach we’ll need in order to add a child element (note that the rest of the SVG file and many of the path attributes have been omitted for clarity - shown below). The new element is pretty self-explanatory: attributeName defines which attribute in the parent element we’re animating, from and to are the start and end values, dur is the duration of the animation, and fill=“freeze” is used to make sure the attribute retains the last value, rather than flipping back to its original value.

Comme avec les animations CSS de la dernière fois, je vais commencer par n’animer que a couleur de remplissage. Celle-ci est invoquée en plaçant la balise <animate> comme un élément enfant de la balise <path>. Au cas où vous ne seriez pas très à l’aise avec le XML, dans le code précédent, le chemin est écrit comme une balise auto-fermante <path … />. : ceci peut légitimement être réécrite comme une balise non auto-fermante : <path …></path>. C’est de cette dernière approche dont nous avons besoin pour ajouter un élément enfant (notez que le reste du fichier SVG et beaucoup d’attributs du chemin ont été omis pour plus de clarté - voir ci-dessous).

Le nouvel élément se comprend bien de lui-même : attributeName définit quel attribut nous animons dans l ‘élément parent , from et to sont les valeurs de début et de fin, dur est la durée de l’animation et « fill=freeze » est utilisé pour s’assurer que l’attribut reste à la dernière valeur, plutôt que de revenir à sa valeur du début.

That’s easy enough, but our original animation wasn’t a simple transition from one value to another, it also had a specific intermediate value, giving us three keyframes in total. That can be achieved with SMIL as well, by replacing our “from” and “to” attributes with “values” and “keyTimes” attributes which hold the three values we want to hit, and the proportion of the way through the animation that each is applied. The values in each list are separated by a semicolon. Code is shown top right. I’m using a generic <animate> element for animating this fill color. There is also a specific <animateColor> element that could be used instead, but since <animate> can do everything that <animateColor> can achieve, plus more, there’s no point using the latter these days. Even the SMIL specification now recommends using <animate> rather than <animateColor>, so who am I to argue.

C’est assez facile, mais notre animation d’origine n’était pas une simple transition d’une valeur à une autre ; elle avait aussi une valeur intermédiaire, nous donnant trois trames-clés au total. Ceci peut être aussi rélaisé avec SMIL en remplaçant nos attributs « from » et « to » par les les attributs « values » et « KeyTimes » qui contiennent les trois valeurs que nous voulons atteindre, et la proportion de déplacement de l’animation à laquelle chacune est appliquée. Dans chacune des listes, ces valeurs sont séparées par des points-virgules. Le code est présenté en haut à droite.

J’utilise l’élément générique <animate> pour animer la couleur de remplissage. Il existe aussi un élément <animateColor> qui pourrait être utilisé à la place, mais, comme <animate> peut faire tout ce que peut réaliser <animateColor>, voire plus, il n’y a pas de raison d’utiliser ce dernier de nos jours. Même la spécification SMIL recommande maintenant d’utiliser <animate> rplutôt que <animateColor>, comme je viens de le montrer.

Our original animation not only changed the fill color, but also the stroke color and width. This obviously entails animating three attributes – which we do just by using three <animate> elements (shown right). Notice that I’ve had to adjust the stroke-width values somewhat to get a similar result to the CSS animated version. I’m not sure why there’s a difference – perhaps the CSS values are interpreted as pixels, whilst the SMIL values are treated as SVG user units, based on the viewBox declared at the start of the file. Whatever the underlying reason, a little tweaking was required but I was nevertheless able to produce the same result. Animating attributes works well where the attribute can hold only a single, simple value, such as a length or color. The “transform” attribute is a more complex case, as it can hold a combination of translate(), rotate, scale(), and skew() functions. If your element already has a transformation applied – as many will do if they’re created in Inkscape – you probably want your animation to be added to the current transformation rather than replacing it entirely. To achieve this requires more than a simple <animate> element; it needs something that understands the syntax and structure of the transform attribute. It needs <animateTransform> (next page, top right).

Notre animation d’origine non seulement modifiait la couleur de remplissage, mais modifiait aussi la couleur et l ‘épaisseur du contour. Ceci implique évidemment d’animer trois attributs - ce que nous pouvons faire simplement en utilisant trois éléments <animate> (montré à droite).

Notez que j’ai du ajuster un peu les valeurs de l’épaisseur du contour pour obtenir un résultat similaire à la version animée avec CSS. Je ne sais as exactement pourquoi cette différence - peut-être que les valeurs du CSS sont interprétées en pixels, alors que celles de SMIL sont traiter dans les unités SVG de l’utilisateur, basées sur la » viewBox » déclarée au début du fichier. Quelque soit la raison sous-jacente, un petit ajustement était nécessaire, mais, néanmoins, je n’ai jamais été capable d’obtenir le même résultat.

Les attributs d’animation fonctionnent bien là où l’attribut ne contient qu’une seule valeur simple, telle qu’une longueur ou une couleur. L’attribut « transform » est un cas plus complexe, car il peut contenir une combinaison des fonctions translate(), rotate, scale() et skew(). Si votre élément a déjà subi une transformation - comme beaucoup le font en créant dans Inkscape - vous voudrez probablement que votre animation soit ajoutée à la transformation courante plutôt que de la remplacer entièrement. Pour le réaliser, ceci demande plus qu’un simple élément <animate> ; quelque chose qui comprend la syntaxe et la structure de l’attribut transform est nécessaire. <animateTransform> est nécessaire (page suivante, en haut à droite).

Here I’ve used a couple of <animateTransform> elements to zoom and rotate the star during the course of its animation. The first element scales the star (type=“scale”), first making it bigger (1 > 1.5) and then smaller (1.5 > 1 > 0.75), covering four keyframes in the five second duration. You might think that attributeName=“transform” is redundant when the element itself is called <animateTransform> – and I would agree with you – but the animation doesn’t work without it. The second element rotates the star. In this case the values each consist of three space- or comma-separated numbers. These represent the amount of rotation (in degrees), and the x and y coordinates to be used as the center of rotation. I’ve selected 40 for each, to put the center roughly in the middle of the star, so it doesn’t spin off-screen entirely.

Thanks to the scale animation, however, it does still move around quite a bit. As the star is scaled in size, so its center point moves and the values in the rotation animation are no longer correct. This could be accommodated, to some extent, by tweaking the x and y coordinates in the rotation, or by adding another animation to set a translate() transform to compensate for the moving center point. A better approach would be to re-draw the star centered on the 0,0 coordinates, then position it on the page by tweaking the transform attribute on the element itself. That way, there’s no need to specify a center point for the rotation, and the values for the “rotate” animation could be reduced to a simple list of angles. You’ll have noticed that both the <animateTransform> elements have an additive=“sum” attribute. SMIL animations can be configured so that the animated values completely replace any previous value on the element, or so that the effects of the animation are cumulative. Without this extra parameter, the scale animation replaces the transform=“translate(20, 20)” attribute that Inkscape created; then the rotate animation replaces the scale animation. The result is that the star only rotates, and doesn’t scale – and it does so in the wrong location. The additive=“sum” attribute tells the browser to keep any existing transforms around, and add the new animated value to them to give a cumulative effect. In other words, the star both zooms and rotates, and does so (roughly) in the location specified by Inkscape’s translate() value.

Over the years, CSS has gained ever more of SVG’s capabilities, with the result that the SMIL animations I’ve shown so far can all be implemented as CSS animations. The fill and stroke we covered last time, but even <animateTransform> has a counterpart in CSS, now that the latter supports a “transform” property that allows elements to be translated, rotated, scaled, and skewed. Unlike SVG, it also offers a few options for transforming your element in three dimensions. But there are still some tricks up the SMIL sleeve which CSS animations can’t compete with (yet). One of these is the ability to animate a path between one shape and another. Much like animating a color, this is just a special case of animating an attribute – in this case the “d” attribute that holds the data representing the shape of a path. As a reminder, here’s what the path data for our star looks like: d=“m 40,15 6,18 19,0 L 49,45 56,64 40,53 24,65 30,45 14,34 34,34 Z”

I’m going to animate the star turning into a large arrow, pointing to the top right of the screen. To do this, I just use another <animate> element, transforming the “d” attribute from its default value to a new path definition. This will do the trick: By commenting out the other <animate> and <animateTransform> elements (using the XML/HTML method of wrapping them in <!– and –> tags), we can see what this path animation looks like in isolation. Here (above) are six frames from the transition. Removing the comment tags to reinstate the other animations results in a star that smoothly changes to an arrow whilst it’s rotating, changing size, and it transitions from a red fill with a thin dark red outline to a blue fill with a thick dark blue outline (via a purple fill along the way). Stacking up multiple individual transitions to create one larger animation is something that SMIL excels at.

It’s important to note that the animated “d” values must all contain the same number of parameters for a smooth transition. Obviously the browser wouldn’t know how to animate from a 5-pointed star to a 12-pointed star; which lines should the new nodes appear on? But the same goes for the other parameters in a “d” attribute – if you want curved lines in your animation, you need to start out with them curved (even if the curvature is visually non-existent) to ensure that each part of the animation contains the same line types and number of coordinates for all the nodes and Bézier control points. If your paths contain different line segments the animation will still take place but, rather than a smooth transition from one shape to another, you’ll get sudden, discontinuous jumps from shape to shape. To my eye, SMIL animation is easier to follow than its CSS counterpart. Admittedly, it’s rather verbose which can result in having to edit a lot of elements to make a simple timing change. But that verbosity also has its advantages, as we’ll see next time – when we’ll also send our star on a trip along a path.

issue136/inkscape.1537166840.txt.gz · Dernière modification : 2018/09/17 08:47 de d52fr