issue149:inkscape
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue149:inkscape [2019/10/01 08:55] – créée d52fr | issue149:inkscape [2019/10/08 16:17] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | Last time, we looked at some different ways to use JavaScript to modify your SVG file dynamically in a web browser. We concluded with a verbose way to create a new SVG element, set its attributes, and append it to an existing element. In this instalment, we’ll build on those same ideas to do even more with our elements – so go ahead and re-read last month’s column if you need a refresher before we plough on. | + | **Last time, we looked at some different ways to use JavaScript to modify your SVG file dynamically in a web browser. We concluded with a verbose way to create a new SVG element, set its attributes, and append it to an existing element. In this instalment, we’ll build on those same ideas to do even more with our elements – so go ahead and re-read last month’s column if you need a refresher before we plough on. |
Our test file last time was made up primarily of an SVG < | Our test file last time was made up primarily of an SVG < | ||
+ | |||
+ | <svg | ||
+ | |||
+ | xmlns=" | ||
+ | |||
+ | viewBox=" | ||
+ | |||
+ | </ | ||
+ | |||
+ | La dernière fois, nous avons regardé différentes façons d' | ||
+ | |||
+ | Notre fichier test de la dernière fois était constitué principalement d'un élément SVG < | ||
<svg | <svg | ||
Ligne 11: | Ligne 23: | ||
</ | </ | ||
- | Okay, that’s admittedly a pretty terse SVG file, even by the standards of this series, but that’s because it doesn’t actually have any content. Instead we’re going to create all the content dynamically, | + | **Okay, that’s admittedly a pretty terse SVG file, even by the standards of this series, but that’s because it doesn’t actually have any content. Instead we’re going to create all the content dynamically, |
var svg = document.querySelector(" | var svg = document.querySelector(" | ||
Ligne 18: | Ligne 30: | ||
This ‘innerHTML’ approach is simple, and can create complex nested structures, but it doesn’t return a ‘handle’ that we can use to further manipulate the created content. What if we now want our red square to be blue? We’ll need to do something like this, relying on the fact that we gave the square an ID: | This ‘innerHTML’ approach is simple, and can create complex nested structures, but it doesn’t return a ‘handle’ that we can use to further manipulate the created content. What if we now want our red square to be blue? We’ll need to do something like this, relying on the fact that we gave the square an ID: | ||
+ | |||
+ | var square1 = document.querySelector("# | ||
+ | |||
+ | square1.setAttribute(" | ||
+ | |||
+ | Bon. J' | ||
+ | |||
+ | var svg = document.querySelector(" | ||
+ | |||
+ | svg.innerHTML = '< | ||
+ | |||
+ | Cette approche « innerHTML » est simple et peut créer des structures imbriquées complexes, mais elle ne retourne aucune « manette » avec laquelle nous pourrions manipuler le contenu créé. Et que faire maintenant si nous voulons que le carré rouge devienne bleu ? Nous aurons besoin de faire quelque chose comme ceci, en nous appuyant sur le fait que nous avons donné un ID (identifiant) au carré : | ||
var square1 = document.querySelector("# | var square1 = document.querySelector("# | ||
Ligne 23: | Ligne 47: | ||
square1.setAttribute(" | square1.setAttribute(" | ||
- | The more long-winded approach we took last time gives us a JavaScript object representing our element which we then use to set all the attributes. But we can hang on to that handle to use later on, if we wish. Let’s add another red square, this time using the verbose method (below): | + | **The more long-winded approach we took last time gives us a JavaScript object representing our element which we then use to set all the attributes. But we can hang on to that handle to use later on, if we wish. Let’s add another red square, this time using the verbose method (below): |
Now if we want to change the color of the second square, we can simply use the same ‘square2’ variable we used when creating it, even though it’s now been added to the page: | Now if we want to change the color of the second square, we can simply use the same ‘square2’ variable we used when creating it, even though it’s now been added to the page: | ||
Ligne 29: | Ligne 53: | ||
square2.setAttribute(" | square2.setAttribute(" | ||
- | I’ll spare you a screenshot – I’m sure you can guess what it looks like now. | + | I’ll spare you a screenshot – I’m sure you can guess what it looks like now.** |
- | So far, we’ve mostly revised the content from last month, but in doing so you’ve got a nice arrangement of two squares, a yellow one on top of a blue one. But why are they in that order? Why isn’t the blue one on top? You might think it’s because we created the blue one first, and the yellow one second – and to some extent you’d be right. But there is a little more to it than that. | + | L' |
+ | |||
+ | Maintenant, si nous voulons changer la couleur du second carré, nous pouvons utiliser simplement la variable « square2 » (carré2) que nous avons utilisée pour le créer, même si il a déjà été ajouté à la page : | ||
+ | |||
+ | square2.setAttribute(" | ||
+ | |||
+ | Je vous épargne une copie d' | ||
+ | |||
+ | **So far, we’ve mostly revised the content from last month, but in doing so you’ve got a nice arrangement of two squares, a yellow one on top of a blue one. But why are they in that order? Why isn’t the blue one on top? You might think it’s because we created the blue one first, and the yellow one second – and to some extent you’d be right. But there is a little more to it than that. | ||
The reason isn’t that we created the squares in a particular chronological order, but rather that they ended up in the XML structure in a particular document order. When we added the second square we used the appendChild() method, which inserts it as the last child of the selected parent, so our XML structure ends up looking roughly like this: | The reason isn’t that we created the squares in a particular chronological order, but rather that they ended up in the XML structure in a particular document order. When we added the second square we used the appendChild() method, which inserts it as the last child of the selected parent, so our XML structure ends up looking roughly like this: | ||
+ | |||
+ | <svg> | ||
+ | <rect id=" | ||
+ | <rect id=" | ||
+ | </ | ||
+ | |||
+ | Jusque-là, nous avons révisé les points du numéro précédent, | ||
+ | |||
+ | La raison n'est pas que nous avons créé les carrés dans un certain ordre chronologique, | ||
<svg> | <svg> | ||
Ligne 40: | Ligne 81: | ||
</ | </ | ||
- | The blue < | + | **The blue < |
- | If you’re familiar with HTML and CSS, you might imagine that you could override this ordering using the “z-index” CSS property. Unfortunately, | + | If you’re familiar with HTML and CSS, you might imagine that you could override this ordering using the “z-index” CSS property. Unfortunately, |
- | So how would we go about putting the blue square on top of the yellow one? It’s a two step operation: first we remove the blue square from the document, but keep it hanging around in memory; then we insert it back into the document, at the end. Given that we’ve already assigned the blue < | + | Le < |
+ | |||
+ | Si vous êtes habitué au HTML et au CSS, vous pourriez imaginer que vous pourriez outrepasser cet ordre en utilisant la propriété « z-index » du CSS. Malheureusement, | ||
+ | |||
+ | **So how would we go about putting the blue square on top of the yellow one? It’s a two step operation: first we remove the blue square from the document, but keep it hanging around in memory; then we insert it back into the document, at the end. Given that we’ve already assigned the blue < | ||
+ | |||
+ | square1.remove(); | ||
+ | |||
+ | svg.appendChild(square1); | ||
+ | |||
+ | Aussi, comment ferons-nous pour placer le carré bleu sur le jaune ? C'est une opération en 2 étapes : d' | ||
square1.remove(); | square1.remove(); | ||
Ligne 50: | Ligne 101: | ||
svg.appendChild(square1); | svg.appendChild(square1); | ||
- | So now we know how to add an object to the top of the image, and how to move an object from a lower level up to the top. What about inserting a new object at the top of the document, so that it appears right at the bottom of the stack? If appendChild() adds it to the end of the document, surely insertChild() will put it at the start? | + | **So now we know how to add an object to the top of the image, and how to move an object from a lower level up to the top. What about inserting a new object at the top of the document, so that it appears right at the bottom of the stack? If appendChild() adds it to the end of the document, surely insertChild() will put it at the start? |
Uh-oh! That’s not so good. The problem is that there’s no XML method called insertChild(), | Uh-oh! That’s not so good. The problem is that there’s no XML method called insertChild(), | ||
+ | |||
+ | svg.insertBefore(square3, | ||
+ | |||
+ | Ainsi, maintenant, nous savons comment ajouter un objet sur le dessus d'une image, et comment déplacer cet objet de dessous vers le dessus. Et si on insérait un nouvel objet en haut du document, de sorte qu'il apparaisse juste en bas de la pile ? Si appendChild() l' | ||
+ | |||
+ | Oh-là ! Ce n'est pas si bon. Le problème est qu'il n'y a pas de méthode appelée inserChild(), | ||
svg.insertBefore(square3, | svg.insertBefore(square3, | ||
- | This is great when you’ve already got a handle to the first child element, but that’s not always the case. Perhaps it was inserted dynamically by some other code, or you’ve just lost track of which element is which. You can always append a new node at the end of the parent’s list of children, so it would be useful to have an equivalent bit of code to insert a new node at the start of the list. Every XML element has a “firstElementChild” property that can be used to retrieve a handle to its first child (skipping any text content) without needing to know anything more about it. We can use this to insert another element at the bottom of the stack (top right). | + | **This is great when you’ve already got a handle to the first child element, but that’s not always the case. Perhaps it was inserted dynamically by some other code, or you’ve just lost track of which element is which. You can always append a new node at the end of the parent’s list of children, so it would be useful to have an equivalent bit of code to insert a new node at the start of the list. Every XML element has a “firstElementChild” property that can be used to retrieve a handle to its first child (skipping any text content) without needing to know anything more about it. We can use this to insert another element at the bottom of the stack (top right). |
- | There’s still a bit of a gap between the yellow and the blue squares. Time to insert an element in the middle of the list of child nodes. As a reminder of where we stand at the moment, switching to the “Inspector” (Firefox) or “Elements” (Chrome) tab in the developer tools will show you the current state of your XML document: | + | There’s still a bit of a gap between the yellow and the blue squares. Time to insert an element in the middle of the list of child nodes. As a reminder of where we stand at the moment, switching to the “Inspector” (Firefox) or “Elements” (Chrome) tab in the developer tools will show you the current state of your XML document:** |
+ | |||
+ | C'est super quand il y a déjà une manette au premier élément enfant, mais ce n'est pas toujours le cas. Il a peut-être été inséré dynamiquement par un autre code, ou vous avez simplement perdu le fil de quel élément il s' | ||
+ | |||
+ | Il reste toujours un peu d' | ||
+ | |||
+ | **To mix things up a little, we’re not going to create a brand new square this time – instead we’ll create a copy of an existing one. In browser terms, we’re going to create a “clone” of the node, but don’t confuse it with Inkscape’s concept of clones – the two are completely different things (Inkscape’s “clones” are actually implemented as SVG <use> elements). First, let’s clone our purple square – which we’ve still got assigned to the “square4” variable – and assign the clone to a highly-imaginatively named variable: | ||
+ | |||
+ | var square5 = square4.cloneNode(true); | ||
+ | square5.id = " | ||
+ | square5.setAttribute(" | ||
+ | square5.setAttribute(" | ||
- | To mix things up a little, we’re not going to create a brand new square this time – instead we’ll create a copy of an existing one. In browser terms, we’re going to create a “clone” of the node, but don’t confuse it with Inkscape’s | + | Pour changer un peu, nous n' |
var square5 = square4.cloneNode(true); | var square5 = square4.cloneNode(true); | ||
Ligne 67: | Ligne 135: | ||
square5.setAttribute(" | square5.setAttribute(" | ||
- | All we needed to do was call the cloneNode() method of the node we wish to duplicate. The “true” parameter ensures that we clone not only the node itself, but any descendants it may have – if we had passed “false” instead, we would get only a duplicate of the node itself. In this case, the results are identical, since our < | + | **All we needed to do was call the cloneNode() method of the node we wish to duplicate. The “true” parameter ensures that we clone not only the node itself, but any descendants it may have – if we had passed “false” instead, we would get only a duplicate of the node itself. In this case, the results are identical, since our < |
- | You’ll also note that I’ve changed the ID of the cloned element. We’re about to put it back into the same document and, although browsers don’t enforce it, the XML rules specifically prohibit duplicate IDs in a single document. For the sake of correctness, | + | You’ll also note that I’ve changed the ID of the cloned element. We’re about to put it back into the same document and, although browsers don’t enforce it, the XML rules specifically prohibit duplicate IDs in a single document. For the sake of correctness, |
- | To insert the clone, we’re just going to use the same insertBefore() method we used earlier. But, this time, our reference element | + | Tout ce que nous avions à faire était d' |
+ | Vous noterez aussi que j'ai changé l'ID de l' | ||
+ | |||
+ | **To insert the clone, we’re just going to use the same insertBefore() method we used earlier. But, this time, our reference element (the one we’re inserting before) will be the blue < | ||
+ | |||
+ | |||
+ | svg.insertBefore(square5, | ||
+ | |||
+ | Pour insérer le clone, nous allons simplement utiliser la même méthode insertBefore() utilisée précédemment. Mais, cette fois, notre élément de référence (celui avant lequel sera faite l' | ||
svg.insertBefore(square5, | svg.insertBefore(square5, | ||
- | As a reminder, the last child is the one that’s drawn on top (the blue square), so inserting just before the last child actually puts the cloned purple square below the blue square in the z-order. | + | **As a reminder, the last child is the one that’s drawn on top (the blue square), so inserting just before the last child actually puts the cloned purple square below the blue square in the z-order. |
The “firstElementChild” and “lastElementChild” properties are useful shortcuts, but you don’t always want to use the first or last child as your reference point. For more general purpose requirements, | The “firstElementChild” and “lastElementChild” properties are useful shortcuts, but you don’t always want to use the first or last child as your reference point. For more general purpose requirements, | ||
Ligne 83: | Ligne 159: | ||
console.log(svg.children.length); | console.log(svg.children.length); | ||
- | |||
- | |||
// Remove the third one | // Remove the third one | ||
Ligne 90: | Ligne 164: | ||
svg.children[2].remove(); | svg.children[2].remove(); | ||
+ | // Remove the penultimate node, regardless of how many there are | ||
+ | svg.children[svg.children.length - 2].remove(); | ||
- | // Remove the penultimate node, regardless of how many there are | + | Souvenez-vous que le dernier enfant est celui qui est dessiné tout au-dessus (le carré bleu) ; donc, une insertion juste avant le dernier enfant met en fait le carré violet cloné sous le carré bleu dans l' |
+ | |||
+ | Les propriétés « firstElementChild » et « lastElementChild » sont des raccourcis utiles, mais vous ne souhaiterez pas toujours utiliser le premier ou le dernier enfant comme référence. Pour les besoins d' | ||
+ | |||
+ | // Combien des nœuds enfants y a-t-il ? | ||
+ | |||
+ | console.log(svg.children.length); | ||
+ | |||
+ | // Enlever le troisième | ||
+ | |||
+ | svg.children[2].remove(); | ||
+ | |||
+ | Enlever l' | ||
svg.children[svg.children.length - 2].remove(); | svg.children[svg.children.length - 2].remove(); | ||
- | Remembering that array (and collection) indexes start at zero, it should be clear why the third child has an index of 2. For the same reason the index of the last child is always “children.length – 1”, so the penultimate node will be “children.length – 2”. Of course if there are fewer than two child nodes present, this call will fail – a real program would have to check the length first, before trying to remove the penultimate child. | + | **Remembering that array (and collection) indexes start at zero, it should be clear why the third child has an index of 2. For the same reason the index of the last child is always “children.length – 1”, so the penultimate node will be “children.length – 2”. Of course if there are fewer than two child nodes present, this call will fail – a real program would have to check the length first, before trying to remove the penultimate child. |
Consider all this in terms of Inkscape: when you move things up and down in the z-order within Inkscape, or move entire layers up and down, what you’re actually doing is removing nodes from the document and reinserting them at a different position. If you’ve got multiple items selected, or a group or layer containing lots of other items, they all have to be removed and reinserted. If you ever find yourself wondering why Inkscape is taking a long time to paste something, now you’ve got an idea of how involved this process actually is! | Consider all this in terms of Inkscape: when you move things up and down in the z-order within Inkscape, or move entire layers up and down, what you’re actually doing is removing nodes from the document and reinserting them at a different position. If you’ve got multiple items selected, or a group or layer containing lots of other items, they all have to be removed and reinserted. If you ever find yourself wondering why Inkscape is taking a long time to paste something, now you’ve got an idea of how involved this process actually is! | ||
- | With the JS you’ve learnt so far, you have enough knowledge to write some code that will move objects around the canvas, as well as up and down in the z-order. You can use document.querySelector() to get a JS handle to an element in your drawing, and setAttribute() to dynamically change its parameters. Next time, we’ll look at how you might use some of these features to animate your SVG image. | + | With the JS you’ve learnt so far, you have enough knowledge to write some code that will move objects around the canvas, as well as up and down in the z-order. You can use document.querySelector() to get a JS handle to an element in your drawing, and setAttribute() to dynamically change its parameters. Next time, we’ll look at how you might use some of these features to animate your SVG image.** |
+ | |||
+ | En se souvenant que les index des tableaux (et des collections) commencent à zéro, il devrait être clair que le troisième enfant a 2 comme index. Pour cette même raison, l' | ||
+ | |||
+ | Regardez tout ceci à la façon d' | ||
+ | |||
+ | Avec le JS que vous avez appris jusqu' | ||
issue149/inkscape.1569912913.txt.gz · Dernière modification : 2019/10/01 08:55 de d52fr