Outils pour utilisateurs

Outils du site


issue145:inkscape

A quick recap on where we got to last time: using CSS classes, we were able to toggle the style of a button by clicking on it. But it worked well only for a simple button with no content. If you clicked on the text inside the button, the toggle wouldn’t work. And you were still able to select the text, which is less than ideal for a button. What we really want to do is to group together several objects, and have a click on any of them act as a trigger for the button. And, with a little more CSS, we can deal with the selectable text issue, too. So let’s begin in Inkscape, by designing a fancier button…

Récapitulons rapidement ce que nous avons vu la dernière fois : en utilisant les classes du CSS, nous avons été capables de basculer le style d'un bouton en cliquant dessus. Mais ça ne marchait bien que si le bouton ne contenait rien. Si vous cliquiez sur le texte à l'intérieur du bouton, la bascule ne marchait pas. Et vous pouviez encore sélectionner le texte, ce qui est loin d'être idéal pour un bouton. Ce que nous voulons vraiment faire, c'est de regrouper plusieurs objets et de faire en sorte qu'un clic sur l'un d'eux agisse comme déclencheur pour le bouton. Et, avec un peu plus de CSS, nous pouvons également traiter le problème du texte sélectionnable. Aussi, commençons, dans Inkscape, par dessiner un bouton plus raffiné.

This button is made up of four objects, each of which has a solid fill color so there are no stroke colors to worry about. When toggled, we’d like to change the background and text colors, and give the impression of the button being ‘pressed in’ by making the top/left object dark and the bottom/right one light. We can therefore draw up a small table showing the type of each object and the colors it will adopt in each state. We’re going to put the entire button into a single group. This isn’t strictly necessary, as Inkscape’s layers are already SVG group objects, but does make it a little easier to work with if we want to add more than one button (or other objects) to a single layer.

Ce bouton est constitué de quatre objets, chacun d'eux ayant une couleur de fond unie et aucune couleur de contour. Lors d'un basculement, nous aimerions modifier les couleurs du fond et du texte et donner l'impression que le bouton a été « enfoncé » en assombrissant l'objet en haut et à gauche de l'objet et en éclaircissant l'objet en bas et àdroite. Nous pouvons par conséquent dessiner un petit tableau montrant le type de chaque objet et les couleurs qu'il adoptera dans chaque état.

Nous mettons tout le bouton dans un seul groupe. Ce n'est pas strictement nécessaire, car les calques d'Inkscape sont déjà des objets du groupe SVG, mais cela facilitera un peu le travail si nous voulons ajouter plus d'un bouton (ou d'autres objets) à un calque unique.

Now it’s time to set up the CSS classes. The basic idea is that we will give the outer group a class of ‘button’, and then toggle an additional ‘clicked’ class on and off using one of the techniques from last time. Let’s start by looking at the structure of the button, as created by Inkscape, but with most of the attributes removed for clarity: <svg> … <g inkscape:label=“Layer 1”> <g id=“g972”> <rect id=“rect10” /> <path id=“path31” /> <path id=“path874” /> <text id=“text958”> <tspan id=“tspan956”>CLICK ME</tspan> </text> </g> </g> </svg>

Maintenant, c'est le moment de paramétrer les classes du CSS. L'idée de base est que nous attribuerons au groupe extérieur une classe « button » (bouton), et ensuite nous basculerons vers une classe additionnelle « clicked » (cliqué) sur arrêt/marche en utilisant l'une des techniques vues la dernière fois. Commençons par regarder la structure du bouton, telle que créée dans Inkscape, mais en ayant retiré la plupart des attributs pour plus de clarté :

<svg> …

<g inkscape:label="Layer 1">
  <g id="g972">
    <rect id="rect10" />
    <path id="path31" />
    <path id="path874" />
    <text id="text958">
      <tspan id="tspan956">CLICK ME</tspan>
    </text>
  </g>
</g>

</svg>

It’s all pretty much as you might expect: a <g> (the layer in Inkscape) containing a <g> (our button) which contains the four objects from the table above. There’s a slight oddity in terms of the <text> object containing a <tspan>, but that’s just down to the way SVG handles text. If we had multiple lines of text in our button, this might make more sense, as all the lines would then be separate <tspan> elements contained within a single <text>, but, even with only one line, Inkscape still uses a <tspan> even though it’s not strictly necessary. To keep the CSS a little clearer, it’s best to change the IDs of some objects, or give them classes to better describe what they do. Otherwise, trying to remember which <path> is which at some point in the future becomes a problem. I tend to use classes for these sorts of labels, so they can be reused in other parts of the file as well. After all, you might want a second button to also have a ‘top-left’ path, so using that string as an ID would become prohibitive (remember, IDs have to be unique in a document, classes don’t).

C'est à peu près tout ce que vous pouviez espérer : un <g> (le calque dans Inkscape) contenant un <g> (notre bouton) qui contient les quatre objets du tableau ci-dessus. Il y a une légère bizarrerie dans les termes de l'objet <text> qui contient un <tspan>, mais ce n'est rien d'autre que la façon pour Inkscape de gérer les textes. Si nous avions plusieurs lignes de texte dans notre bouton, cela aurait plus de sens, car toutes les lignes seraient alors des éléments <tspan> individuels avec un unique <text> ; mais, même avec une seule ligne, Inkscape utilise toujours un <tspan>, bien que ce ne soit pas strictement nécessaire.

Pour garder le CSS un peu plus clair, il vaut mieux changer l'identifiant (ID) de certains objets, ou leur donner des classes pour mieux décrire ce qu'ils font. Autrement, le problème est qu'il arrivera un moment où il sera difficile de se souvenir de quel <path> (chemin) il s'agit. J'ai tendance à utiliser les classes pour ces espèces d'étiquettes, afin qu'elles puissent aussi être réutilisées dans d'autres parties du fichier. Après tout, vous pourriez souhaiter qu'un second bouton ait un chemin « haut-gauche » ; ainsi, l'utilisation de cette chaîne de caractères comme ID deviendrait rédhibitoire (souvenez-vous que les ID sont uniques dans un document, pas les classes).

With the addition of a class for the button group, and one each for the paths, we’ve basically got this structure: <g class=“button”> <rect /> <path class=“top-left” /> <path class=“bottom-right” /> <text> <tspan>CLICK ME</tspan> </text> </g>

Avec l'ajout d'une classe dans le groupe du bouton, et d'une à chaque chemin, nous avons en gros cette structure :

<g class=“button”>

<rect />
<path class="top-left" />
<path class="bottom-right" />
<text>
  <tspan>CLICK ME</tspan>
</text>

</g>

Now it’s time to add our CSS rules. We’ll use the immediate child selector (>) to ensure that these rules apply only to elements inside our button, so there’s no danger of all the text in the document becoming blue. Compare these rules with the table earlier in this document and you should be able to see what they’re doing: <svg> … <style> .button > rect { fill: #000080; } .button > .top-left { fill: #ffffff; } .button > .bottom-right { fill: #00002e; } .button > text { fill: #a6a6ff; } </style> <g inkscape:label=“Layer 1”> … </g> </svg>

Maintenant, c'est le moment d'ajouter nos règles du CSS. Nous utiliserons le sélecteur immédiat d'enfants (>) pour nous assurer que ces règles s'appliquent uniquement aux éléments de notre bouton ; ainsi, il n'y a aucun danger que tout le texte du document devienne bleu. Comparez ces règles avec celles du tableau précédent de cet article et vous devriez être capable de voir ce qu'elles font :

<svg> … <style> .button > rect {

fill: #000080;

}

.button > .top-left {

fill: #ffffff;

}

.button > .bottom-right {

fill: #00002e;

}

.button > text {

fill: #a6a6ff;

} </style>

<g inkscape:label=“Layer 1”> … </g> </svg>

Don’t forget to also remove any explicit fill and color properties in the ‘style’ attributes of your elements (including the <tspan>), so that the CSS rules you’ve added aren’t overridden. If you load the image into a web browser, it should look the same as the original version in Inkscape. If you’re not sure that your styles are working, or that you’ve removed all the overriding properties on the elements themselves, try temporarily changing the colors in the CSS to other values and confirm that it has an effect when you reload the page. Take a careful look at each CSS rule to make sure you understand what’s happening. Pay particular attention to the difference between an element selector (eg. ‘rect’) and a class selector (with a dot – eg. ‘.button’). So, in this case, ‘.button > rect’ (matches any <rect> that is an immediate child of an element with the ‘button’ class), and ‘.button > .top-left’ (matches any element with the ‘top-left’ class that is an immediate child of an element with the ‘button’ class). Spotting the difference between a class, ID, and element can be tricky. The syntax for CSS is excessively terse, and less than obvious if you’re not used to it, but it’s the language we’re stuck with so we’ll have to make the most of it.

N'oubliez pas de supprimer aussi toutes les propriétés explicites de remplissage et de couleur dans les attributs « style » de vos éléments (y compris le <tspan>), de sorte que les règles du CSS que vous avez ajoutées ne soient pas remplacées. Si vous chargez l'image dans un navigateur Web, elle devrait être semblable à la version originale d'Inkscape. Si vous n'êtes pas sûr que vos styles fonctionnent ou d'avoir supprimé toutes les propriétés qui s'imposeraient dans les éléments eux-mêmes, essayez temporairement de modifier les couleurs dans le CSS par d'autres valeurs et confirmez que ça a un effet quand vous rechargez l'image.

Vérifiez attentivement chaque règle du CSS pour vous assurer que vous comprenez ce qui arrive. Soyez particulièrement attentif à la différence entre un sélecteur d'élément (par ex., « rect ») et un sélecteur de classe (avec un point, par ex., « .button »). Ainsi, dans ce cas, « .button > rect » (fait correspondre tout <rect> qui est l'enfant direct d'un élément avec la classe « button ») et « .button > .top-left » (fait correspondre tout élément ayant la classe « top-left » et qui est l'enfant direct d'un élément avec la classe « button »). Faire la différence entre une classe, un ID et un élément peut s'avérer délicat. La syntaxe du CSS est excessivement laconique et peu évidente si vous n'y êtes pas habitué, mais c'est le langage auquel nous nous astreignons ; aussi, nous devrons en tirer le meilleur parti.

If everything is working okay at this point, it’s time to add another set of rules that will apply when the <g> has both the ‘button’ and the ‘clicked’ classes set. In this case, you just have to concatenate the class selectors – but make sure not to add any spaces between them, as that signifies an ancestor-descendent relationship. Yeah, the syntax of CSS really is that terse. Here’s an example of the additional rule for the <rect>, complete with the new color from the table earlier in the article. I’ll leave it as an exercise for the reader to create the remaining three CSS rules. .button.clicked > rect { fill: #800000; } You can test your new CSS rules by manually adding an extra ‘clicked’ class to the group (so that it reads class=“button clicked”), saving the file, and reloading the page. Remove the extra class and save again before proceeding.

Si tout fonctionne bien à ce stade, c'est le moment d'ajouter un autre jeu de règles qui s'appliqueront quand les classes « button » et « clicked » seront toutes les deux paramétrées. Dans ce cas, il faut simplement concaténer les sélecteurs de classes, mais assurez-vous de n'ajouter aucun espace entre eux, car elle marque une relation ascendant-descendant. Eh oui ! La syntaxe du CSS est vraiment laconique.

Voici un exemple de règle additionnelle pour le <rect>, complétée par la couleur prévue dans le tableau précédent de l'article. Je le laisserai au lecteur comme exercice la création des trois règles du CSS restantes.

.button.clicked > rect {

fill: #800000;

}

Vous pouvez tester manuellement vos nouvelles règles du CSS en ajoutant une classe « clicked » supplémentaire au groupe (ce qui se lit class=“button clicked”), en sauvegardant le fichier et en rechargeant la page. Supprimez la classe supplémentaire et sauvegardez à nouveau avant de poursuivre.

Open the file in Inkscape and select the group that represents the button. In the Object Properties dialog, expand the ‘interactivity’ section and add the following one-liner to the ‘onclick’ field (this should be familiar from last month’s column): this.classList.toggle('clicked'); Save your file, load it into your browser and, if everything has gone smoothly, you should find that clicking on your button toggles it between the two states. One advantage of wrapping everything in a group, and applying the code to that outer layer, is that clicks on any part of the button are passed through to the enclosing element. This avoids our previous problem whereby clicks on the text didn’t toggle the button. But we still have an issue with the text being selectable. We can address this with the ‘pointer-events’ CSS rule, which lets us tell the browser that all mouse activity over the text – including clicks and selection – should be ignored. Modify your first set of rules so that the last one looks like this: .button > text { fill: #a6a6ff; pointer-events: none; }

Ouvrez le fichier dans Inkscape et sélectionnez le groupe qui représente le bouton. Dans le dialogue des Propriétés de l'objet, ouvrez la section Interactivité et ajoutez ce qui suit sur une ligne dans le champ « onclick » (vous y êtes habitué depuis l'article du mois dernier) :

this.classList.toggle('clicked');

Enregistrez votre fichier, chargez-le dans votre navigateur et, si tout se passe comme il faut, vous trouverez qu'en cliquant sur le bouton il bascule entre les deux états.

L'avantage de tout empaqueter dans un groupe et d'appliquer le code au calque extérieur, c'est qu'un clic sur n'importe quelle partie du bouton est transmis à l'élément enveloppant. Cela évite notre précédent problème où un clic sur le texte ne modifiait pas le bouton. Mais nous avons toujours un problème avec le texte qui reste sélectionnable. Nous pouvons le résoudre avec une règle du CSS « pointer-events », qui nous permet de dire au navigateur que les actions de la souris sur le texte - y compris les clics et la sélection - doivent être ignorées. Modifiez le premier jeu de règles de telle sorte que la dernière ressemble à ça :

.button > text {

fill: #a6a6ff;
pointer-events: none;

}

That deals with the selectability problem, but we can go a step further in making our button seem clickable. By adding a ‘cursor’ property to the group itself, we can make the mouse pointer change when it moves over the button. Add this rule to the CSS: .button { cursor: pointer; } Save, reload, and move your mouse pointer over the button to see the effect.

Le problème de sélectivité est ainsi résolu, mais nous pouvons aller un peu plus loin en faisant que notre bouton paraisse cliquable. En ajoutant la propriété « cursor » (curseur) au groupe lui-même, nous pouvons faire changer le pointeur de la souris quand il passe sur le bouton. Ajoutez cette règle au CSS :

.button {

cursor: pointer;

}

Previously, I said I would show you how to make clicks on one element have an effect on a completely different one, but I’ve run out of space in this article, so that will have to wait until next time. Until then, however, you now know how to use CSS classes to style more complex collections of objects, allowing for the creation of much fancier buttons. You also know how to respond to clicks in such a collection simply by putting the code onto a group that wraps all the content. Why not spend the next month designing ever more impressive buttons? There are plenty of tutorials online for different styles if you’re stuck for inspiration. You don’t just have to make them toggle when clicked: a common effect is to apply a class in the ‘onmouseover’ field, and remove it in the ‘onmouseout’. You could even go the whole hog and create a button that has both a mouseover effect and a click effect. And next time, I promise, I will show you how to hook your new buttons up to other elements on your page.

Précédemment, j'ai dit que je vous montrerais comment faire pour que les clics sur un élément aient un effet sur un élement complètement différent, mais je manque de place dans cet article ; aussi, ça attendra la prochaine fois. Cependant, jusque-là, vous savez maintenant comment utiliser les classes du CSS pour traiter le style des ensembles plus complexes d'objets, vous permettant de créer des boutons plus raffinés. Vous pouvez maintenant répondre aux clics sur de tels ensembles en mettant simplement le code sur le groupe qui enveloppe tout le contenu.

Pourquoi ne pas passer le prochain mois à concevoir des boutons de plus en plus impressionnants ? Il y a plein de tutoriels en ligne pour différents styles si vous manquez d'imagination. Ne vous limitez pas à les voir changer d'état sur un clic : un effet classique est d'appliquer une classe sur le champ « onmouseover » et de l'enlever dans « onmouseout ». Vous pouvez même aller jusqu'au bout et créer un bouton qui a, à la fois, l'effet du survol et celui du clic. Et la prochaine fois, je vous le promets, je vous montrerai comment accrocher vos nouveaux boutons à d'autres éléments de votre page.

issue145/inkscape.txt · Dernière modification : 2019/06/13 16:29 de auntiee