Outils pour utilisateurs

Outils du site


issue146:inkscape

Différences

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

Lien vers cette vue comparative

Prochaine révision
Révision précédente
issue146:inkscape [2019/07/02 11:24] – créée auntieeissue146:inkscape [2019/07/17 06:56] (Version actuelle) andre_domenech
Ligne 1: Ligne 1:
-If you followed last month’s tutorial, you should now have a styled button that toggles between two classes when you click on it. This month, we’re going to extend the code behind that button to control other objects on the screen, so if you didn’t play along with the previous article, now is the time to go back and give it a try.+**If you followed last month’s tutorial, you should now have a styled button that toggles between two classes when you click on it. This month, we’re going to extend the code behind that button to control other objects on the screen, so if you didn’t play along with the previous article, now is the time to go back and give it a try.
  
-We’ve previously looked at two ways to put JavaScript into an Inkscape file: directly in the fields within the “Interactivity” section of the Object Properties dialog; and via the “Embedded scripts” tab in the “Scripting” section of the Document Properties dialog. You may recall that the latter location also includes a second tab, labelled “External scripts”. This month we’ll take a look at that tab, and discuss the pros and cons of this approach.+We’ve previously looked at two ways to put JavaScript into an Inkscape file: directly in the fields within the “Interactivity” section of the Object Properties dialog; and via the “Embedded scripts” tab in the “Scripting” section of the Document Properties dialog. You may recall that the latter location also includes a second tab, labelled “External scripts”. This month we’ll take a look at that tab, and discuss the pros and cons of this approach.**
  
-Firstload the SVG file for the button that you created last time into InkscapeThen open the File > Document Properties dialogand select the “Scripting” tab. Within that section make sure the “External scripts” tab is active.+Si vous avez suivi le tutoriel du mois derniervous devriez avoir un bouton décoré qui passe d'une classe à l'autre quand on clique dessusCe mois-cinous allons augmenter le code au-delà de ce bouton pour contrôler d'autres objets à l'écran ; aussi, si vous n'avez pas suivi l'article précédent, il est temps maintenant de revenir en arrière pour l'essayer.
  
-As with the “Embedded scripts” tab, the UI here is sparse and slightly misleading. At the top is an excessively short area that lists any external script files linked to from your document – it should be empty at the momentBelow that is an unlabelled linewith Plus (+) and Minus (-) buttons after it, the latter being disabled at this point. As the name of the tab suggests, this UI is used to link external scripts – i.e. JavaScript code stored in a separate file – to your SVG file. You have probably also guessed that the Plus button adds a file to the list above, whilst the minus button removes it. What isn’t so clear is that the Plus button actually works in three different ways, depending on the content of the unlabelled fieldand whether or not your JS file exists yet.+Nous avons vu précédemment deux façons de mettre du JavaScript dans un fichier Inkscape : directement dans les champs de la section « Interactivité » du dialogue des Propriétés de l'objet, et via l'onglet des « scripts incorporés » dans la section « Scripts » du dialogue des Propriétés du document. Vous vous rappelez sans doute que ce dernier emplacement inclut aussi un second ongletappelé « Scripts externes ». Ce mois-cinous regarderons cet onglet et présenterons les pour et les contre de cette approche.
  
-Method 1: If you just click on the Plus button, you’ll be presented with a file selector dialog. You can then navigate to the directory of your choice and enter a new filename into the file selector. When you accept the content of the file selector (e.g. by clicking the “Open” button), the full path and name of your file will appear in the list at the top of the dialog. NOTE: This does not actually create the file on-disk, so you’ll need to do that manually, opening up the possibility of typos.+**First, load the SVG file for the button that you created last time into Inkscape. Then open the File > Document Properties dialog, and select the “Scripting” tab. Within that section make sure the “External scripts” tab is active. 
 + 
 +As with the “Embedded scripts” tab, the UI here is sparse and slightly misleading. At the top is an excessively short area that lists any external script files linked to from your document – it should be empty at the moment. Below that is an unlabelled line, with Plus (+) and Minus (-) buttons after it, the latter being disabled at this point. As the name of the tab suggests, this UI is used to link external scripts – i.e. JavaScript code stored in a separate file – to your SVG file. You have probably also guessed that the Plus button adds a file to the list above, whilst the minus button removes it. What isn’t so clear is that the Plus button actually works in three different ways, depending on the content of the unlabelled field, and whether or not your JS file exists yet.** 
 + 
 +D'abord, chargez dans Inkscape le fichier SVG du bouton que vous avez créé la dernière fois. Puis ouvrez le dialogue Fichier > Propriétés du document et sélectionnez l'onglet « Scripts ». Dans cette section, assurez-vous que l'onglet « Scripts externes » est actif. 
 + 
 +Comme pour l'onglet « Scripts incorporés », l'interface utilisateur est ici spartiate et légèrement trompeur. En haut il y a une zone excessivement petite où sont listés les fichiers des scripts externes liés à votre document - elle devrait être vide pour l'instant. Juste en dessous se trouve une ligne sans étiquette, suivie de boutons Plus (+) et Moins (-), ce dernier étant inactif actuellement. Comme le nom de l'onglet le suggère, cet interface utilisateur est utilisé pour relier des scripts externes - c-à-d, du code JavaScript dans un fichier séparé - à votre fichier SVG. Vous avez aussi probablement deviné que le bouton Plus ajoute un fichier à la liste du dessus, alors que le bouton Moins l'enlève. Ce qui n'est pas clair, c'est que le bouton Plus fonctionne en fait de trois façons différentes, selon le contenu du champ sans étiquette et si votre fichier JS existe déjà ou pas. 
 + 
 +**Method 1: If you just click on the Plus button, you’ll be presented with a file selector dialog. You can then navigate to the directory of your choice and enter a new filename into the file selector. When you accept the content of the file selector (e.g. by clicking the “Open” button), the full path and name of your file will appear in the list at the top of the dialog. NOTE: This does not actually create the file on-disk, so you’ll need to do that manually, opening up the possibility of typos.
  
 Method 2: This is the same as the previous method, except this time you use the file selector to choose a file that already exists. Once again, the full path to the file is put into the list at the top. This has the advantage over the previous method that you can’t make a typo with the filename. Method 2: This is the same as the previous method, except this time you use the file selector to choose a file that already exists. Once again, the full path to the file is put into the list at the top. This has the advantage over the previous method that you can’t make a typo with the filename.
  
-Method 3: Type something into the unlabelled box, then click the Plus button. Whatever you typed will be added to the list of files at the top of the dialog. Of course, it only really makes sense to type the name (and possibly path) of a JavaScript file, but this field does no error checking so typos and bad paths are all too easy to introduce.+Method 3: Type something into the unlabelled box, then click the Plus button. Whatever you typed will be added to the list of files at the top of the dialog. Of course, it only really makes sense to type the name (and possibly path) of a JavaScript file, but this field does no error checking so typos and bad paths are all too easy to introduce.**
  
-You might think that the third method is to be avoided – the possibility of making a typo is too high. But, in practice, this is the only method of the three that I recommend using! In just about every case, you will want to keep the JavaScript file close to your SVG fileif not in the same directorythen usually just one level away in a “scripts” or “resources” folderThe third method lets you supply just the filenameor a relative path and filename (eg‘scripts/button.js’)which will still be valid if you move your SVG and JS files to another machineor a different location on your hard drive.+Méthode 1 Si vous cliquez simplement sur le bouton Plusun dialogue de sélection de fichier vous est présentéVous pouvez alors naviguer jusqu'au répertoire de votre choix et entrer le nouveau fichier dans le sélecteur de fichier. Quand vous acceptez le contenu du sélecteur de fichier (c'est-à-direen cliquant sur le bouton Ouvrir), le chemin complet et le nom du fichier apparaîtront en haut du dialogueNOTE : Ceci ne crée pas vraiment un fichier sur le disque ; aussivous devrez le faire manuellementouvrant ainsi la possibilité d'erreurs.
  
-The first two methodson the other handproduce absolute paths which will break as soon as the files are movedAnd you can’t edit the paths within this dialog – you have to modify them via the XML editor. So not only is there a chance of introducing typos as you edit thembut you have to be comfortable with using the XML editor to do soBetter, I think, to use method 3 and just be careful with what you type.+Méthode 2 : C'est la même chose que la méthode précédentesauf quecette fois, vous utilisez le sélecteur de fichier pour choisir un fichier qui existe déjàEncore une foisle chemin complet du fichier est placé au sommet de la listeL'avantage ici est que vous ne pouvez pas faire de coquille avec le nom du fichier.
  
-To keep things simple, let’s create a new JavaScript file in the same directory as the main SVG file. Using a text editor, create a new file containing the following line:+Méthode 3 : Tapez quelque chose dans le champ sans étiquette, puis cliquez sur le bouton Plus. Ce que vous avez tapé se retrouve ajouté au sommet de la liste. Bien sûr, ça n'a vraiment de sens qu'en tapant le nom (et éventuellement le chemin) d'un fichier JavaScript, mais ce champ ne fait pas de vérification ; aussi, les erreurs et les mauvais chemins sont très faciles à introduire. 
 + 
 +**You might think that the third method is to be avoided – the possibility of making a typo is too high. But, in practice, this is the only method of the three that I recommend using! In just about every case, you will want to keep the JavaScript file close to your SVG file: if not in the same directory, then usually just one level away in a “scripts” or “resources” folder. The third method lets you supply just the filename, or a relative path and filename (eg. ‘scripts/button.js’), which will still be valid if you move your SVG and JS files to another machine, or a different location on your hard drive. 
 + 
 +The first two methods, on the other hand, produce absolute paths which will break as soon as the files are moved. And you can’t edit the paths within this dialog – you have to modify them via the XML editor. So not only is there a chance of introducing typos as you edit them, but you have to be comfortable with using the XML editor to do so. Better, I think, to use method 3 and just be careful with what you type.** 
 + 
 +Vous pourriez penser que la méthode 3 est à éviter ; la possibilité de faire une erreur est trop grande. Mais, en pratique, c'est la seule des trois méthodes que je recommande d'utiliser ! Dans à peu près tous les cas, vous voudrez garder le fichier JavaScript près de votre fichier SVG : si ce n'est pas dans le même répertoire, c'est dans un dossier « scripts » ou « ressources » juste en dessous. La troisième méthode vous permet de ne spécifier que le nom du fichier ou un chemin relatif et le nom (par ex, « scripts/button.js »), qui restera correct si vous déplacez vos fichiers SVG et JS sur une autre machine ou dans un autre endroit de votre disque dur. 
 + 
 +En revanche, les deux premières méthodes produisent des chemins absolus qui seront erronés dès que les fichiers seront déplacés. Et vous ne pouvez pas modifier les chemins dans le dialogue - vous devez les modifier via l'éditeur XML. Ainsi, non seulement le risque d'introduire des coquilles en les modifiant existe, mais vous devez être à l'aise avec l'éditeur XML pour le faire. Il vaut mieux, je pense, utiliser la méthode 3 en faisant bien attention à ce que vous tapez. 
 + 
 +**To keep things simple, let’s create a new JavaScript file in the same directory as the main SVG file. Using a text editor, create a new file containing the following line:
  
 alert("Loaded"); alert("Loaded");
Ligne 23: Ligne 41:
 Save the file to the same directory as your SVG image, with a “.js” extension. In my case the Inkscape file is called “button.svg”, so I’ll give the JavaScript file the name of “button.js” for clarity, though it’s not a requirement for them to share the same name. Back in the Document Properties dialog, I can now type the filename (with no path) into the unlabelled text field, then click the Plus button to add it to the list at the top, so the dialog looks like this: Save the file to the same directory as your SVG image, with a “.js” extension. In my case the Inkscape file is called “button.svg”, so I’ll give the JavaScript file the name of “button.js” for clarity, though it’s not a requirement for them to share the same name. Back in the Document Properties dialog, I can now type the filename (with no path) into the unlabelled text field, then click the Plus button to add it to the list at the top, so the dialog looks like this:
  
-If everything has been done correctly, loading the SVG file into a browser should result in an alert being shown containing the word “Loaded”. That, at least, tells us that the link from SVG to JS files is working. It’s better to do a lightweight test like this first, before fleshing out your JavaScript code, to make sure the basics are in place.+If everything has been done correctly, loading the SVG file into a browser should result in an alert being shown containing the word “Loaded”. That, at least, tells us that the link from SVG to JS files is working. It’s better to do a lightweight test like this first, before fleshing out your JavaScript code, to make sure the basics are in place.**
  
-We want our button to control another object when it’s clicked – which will be a lot easier if we actually have another object to control! In Inkscape, alter the file to add a simple filled circle, making sure to give it a sensible ID via the Object Properties dialog (I called mine “redCircle”).+Pour rester simple, créons un nouveau fichier JavaScript dans le même répertoire que le fichier SVG principal. En utilisant l'éditeur de texte, créez un nouveau fichier contenant la ligne suivante : 
 + 
 +alert("Loaded"); 
 + 
 +Enregistrez le fichier dans le même répertoire que votre image SVG, avec une extension « .js ». Dans mon cas, le fichier Inkscape s'appelle « button.svg » ; aussi, je donne au fichier JavaScript le nom « button.js » pour plus de clarté, bien qu'il n'y ait aucune obligation qu'ils aient le même nom. Dans le dialogue des Propriétés du document, je peux maintenant taper le nom du fichier (sans le chemin) dans le champ sans étiquette, puis cliquer sur le bouton Plus pour l'ajouter en haut de la liste ; le dialogue ressemble alors à ceci : 
 + 
 +Si tout a été fait correctement, le chargement du fichier SVG dans le navigateur devrait entraîner l'affichage d'une alerte contenant le mot « Loaded » (Chargé). Ceci vous montre, au minimum, que le lien entre les fichiers SVG et JS fonctionne. C'est mieux de faire un test simple comme celui-ci en premier, avant d'étoffer votre code JavaScript, pour s'assurer que les bases sont en place. 
 + 
 +**We want our button to control another object when it’s clicked – which will be a lot easier if we actually have another object to control! In Inkscape, alter the file to add a simple filled circle, making sure to give it a sensible ID via the Object Properties dialog (I called mine “redCircle”).
  
 Right-click on the button, and bring up the Object Properties dialog. Within the “Interactivity” section at the bottom, remove any existing code then, in the “onclick” field, add the following JavaScript function call: Right-click on the button, and bring up the Object Properties dialog. Within the “Interactivity” section at the bottom, remove any existing code then, in the “onclick” field, add the following JavaScript function call:
Ligne 37: Ligne 63:
 } }
  
-Save both files, then reload the SVG file in a web browser, confirming that both elements are visible, and that a click on the button shows the new alert() dialog.+Save both files, then reload the SVG file in a web browser, confirming that both elements are visible, and that a click on the button shows the new alert() dialog.**
  
-Now that we’ve got a function that runs when the button is clickedwe want to populate it with some code to change the fill color of the circle. Previouslywe’ve changed the fill color of the object being clickedeither by explicitly setting “this.style.fill”, or by modifying the classes of the clicked object using “this.classList.toggle()” and similar functions. Altering the style of a different object is essentially the same, except that we no longer use “this” to identify the target for our changes. Instead we need to get a reference to the target object in a different way.+Nous voulons que notre bouton pilote un autre objet quand il est cliquéce qui sera plus facile si nous avons un autre objet à piloter ! Dans Inkscapemodifiez le fichier pour ajouter un simple cercle remplien vous assurant de lui donner un ID logique via le dialogue des Propriétés de l'objet (J'ai appelé le mien « redCircle »).
  
-Depending on exactly what you are trying to dothere are various approaches that could be usedBut the simplestat least conceptuallyare a pair of methods on the “document” object (which exists implicitly on all XML and HTML documents): querySelector() and querySelectorAll(). The difference between them is that the former returns a single XML nodewhereas the latter returns a collection of nodes. A collection is similar in some respects to an array in JSbut doesn’t have all the standard array methodsso needs to be treated a little differently. For this example, however, we want to change the style of only a single element, so document.querySelector() will do the job.+Par un clic droit sur le boutonouvrez le dialogue des Propriétés de l'objetEn basdans la section « Interactivité »enlevez tout code existantpuisdans le champ « onclick »ajoutez l'appel de fonction en JavaScript suivant :
  
-Both methods take a single parameter: a string containing a CSS selector. If the selector matches more than one element then querySelector() just returns the first one. If it matches no elements, the method returns “null”. In JavaScript terms, “null” is what’s referred to as a “falsey” value – that is, one that evaluates to “false” when you use it in an “if” statement. That makes it pretty simple to write defensive code that won’t fall over if your CSS selector doesn’t match anything. Let’s take a look at an example, by replacing the alert() in your buttonPressed() function (top right).+buttonPressed(); 
 + 
 +Cette fonction n'existe pas encore : nous devons l'ajouter à notre fichier JS. En utilisant un éditeur de texte,  enlevez l'alerte existante et remplacez-la par ceci : 
 + 
 +function buttonPressed() { 
 +  alert("Button pressed"); 
 +
 + 
 +Enregistrez les deux fichiers puis rechargez le fichier SVG dans votre navigateur, confirmant que les deux éléments sont visibles et qu'un clic sur le bouton montre le nouveau dialogue alert(). 
 + 
 +**Now that we’ve got a function that runs when the button is clicked, we want to populate it with some code to change the fill color of the circle. Previously, we’ve changed the fill color of the object being clicked, either by explicitly setting “this.style.fill”, or by modifying the classes of the clicked object using “this.classList.toggle()” and similar functions. Altering the style of a different object is essentially the same, except that we no longer use “this” to identify the target for our changes. Instead we need to get a reference to the target object in a different way. 
 + 
 +Depending on exactly what you are trying to do, there are various approaches that could be used. But the simplest, at least conceptually, are a pair of methods on the “document” object (which exists implicitly on all XML and HTML documents): querySelector() and querySelectorAll(). The difference between them is that the former returns a single XML node, whereas the latter returns a collection of nodes. A collection is similar in some respects to an array in JS, but doesn’t have all the standard array methods, so needs to be treated a little differently. For this example, however, we want to change the style of only a single element, so document.querySelector() will do the job.** 
 + 
 +Maintenant que nous avons une fonction qui est lancée quand on clique sur le bouton, nous voulons la remplir avec un peu de code pour changer la couleur de remplissage du cercle.  Auparavant, nous avons changé la couleur de remplissage de l'objet cliqué, soit en paramétrant explicitement « this.style.fill », soit en modifiant les classes de l'objet cliqué en utilisant « this.classList.toggle() » et des fonctions similaires. La modification du style d'un objet différent est en gros identique, sauf que nous n'utilisons plus « this » pour identifier la cible de nos modifications. À la place, nous devons donner la référence de l'objet ciblé d'une autre manière. 
 + 
 +Selon ce que nous essayons de faire, il y a plusieurs approches qui peuvent être utilisées. Mais les plus simples, au moins conceptuellement, sont deux méthodes sur l'objet « document » (qui existe implicitement pour tous les documents XML et HTML) : querySelector() et querySelectorAll(). Leur différence est que la première renvoie un simple nœud XML, alors que la seconde retourne une collection de nœuds. D'une certaine manière, une collection est similaire à un tableau en JS, mais elle n'a pas toutes les méthodes classiques du tableau ; aussi, elle nécessite un traitement un peu différent. Pour cet exemple, cepandant, nous voulons changer le style d'un seul élément ; aussi, document.querySelector() fera l'affaire. 
 + 
 +**Both methods take a single parameter: a string containing a CSS selector. If the selector matches more than one element then querySelector() just returns the first one. If it matches no elements, the method returns “null”. In JavaScript terms, “null” is what’s referred to as a “falsey” value – that is, one that evaluates to “false” when you use it in an “if” statement. That makes it pretty simple to write defensive code that won’t fall over if your CSS selector doesn’t match anything. Let’s take a look at an example, by replacing the alert() in your buttonPressed() function (top right).
  
 Save the JS file, then reload the SVG in the browser. With the developer tools open (press F12, if necessary), and the console tab selected, click on the button in your file. You should see the <circle> element logged out – or the string “No circle found!” otherwise. If you saw the latter, it suggests that the CSS query doesn’t suit the structure of your file. Here are a few things you can look at to help troubleshoot this: Save the JS file, then reload the SVG in the browser. With the developer tools open (press F12, if necessary), and the console tab selected, click on the button in your file. You should see the <circle> element logged out – or the string “No circle found!” otherwise. If you saw the latter, it suggests that the CSS query doesn’t suit the structure of your file. Here are a few things you can look at to help troubleshoot this:
Ligne 49: Ligne 93:
 • Does the ID match the one you put on the circle in Inkscape? • Does the ID match the one you put on the circle in Inkscape?
 • Try changing the selector to match an element (eg. “circle”) instead of an ID. • Try changing the selector to match an element (eg. “circle”) instead of an ID.
-• Open your SVG file in a text editor and search for your ID. Is it definitely present in an ID attribute on the element you expected?+• Open your SVG file in a text editor and search for your ID. Is it definitely present in an ID attribute on the element you expected?** 
 + 
 +Les deux méthodes n'ont besoin que d'un seul paramètre : une chaîne contenant un sélecteur de CSS. Si le sélecteur correspond à plus d'un élement, alors querySelector() ne renvoie que le premier. Si aucun élément ne correspond, la méthode retourne « null ». En termes JavaScript, « null » est ce qui fait référence à une valeur « faussée » - autrement dit, une qui est évaluée « fausse » quand vous l'utilisez dans une déclaration « if ». Ceci facilite beaucoup l'écriture d'un code préventif qui ne plante pas si votre sélecteur de CSS ne correspond à rien. Regardons un exemple, en remplaçant alert() dans votre fonction buttonPressed() (en haut à droite). 
 + 
 +Enregistrez le fichier JS, puis rechargez le fichier SVG dans votre navigateur. Les outils du développeur étant ouverts (appuyez sur F12, si nécessaire), et l'onglet Console étant sélectionné, cliquez sur le bouton dans votre fichier. Vous devriez voir l'élément <circle> journalisé ou la chaîne « No circle found! » (aucun cercle trouvé). Si vous voyez le dernier message, ça suggère que la requête CSS ne correspond pas à la structure de votre fichier. Voici quelques points que vous pouvez regarder pour vous aider à résoudre ce problème : 
 +••Vous souvenez-vous d'avoir mis « # » devant l'ID dans le CSS ? 
 +••Est-ce que l'ID correspond à celui que vous avez donné au cercle dans Inkscape ? 
 +••Essayez de changer le sélecteur pour qu'il corresponde à un élément (par ex., « circle ») plutôt qu'à un ID. 
 +••Ouvrez votre fichier SVG dans un éditeur de texte et cherchez votre ID. Est-il vraiment présent dans un attribut d'ID sur l'élement auquel vous pensez ? 
 + 
 + 
 +**Now that we’ve got a reference to the circle, it’s a pretty simple task to set the style explicitly, or modify its class list. Here’s the buttonPressed() function (below) rewritten to directly set the fill color on the circle. Note that I’ve removed the “else”, as we just want the code to fail silently with no side-effects if the CSS selector fails to match anything. 
 + 
 +Despite what I said earlier, the querySelector() method doesn’t actually return the SVG node, as such, but rather a JavaScript object that references the element in the browser’s internal document structure. Usually you can ignore this subtle distinction, but it does mean that we have a JS object in hand, which offers us a few advantages when writing our code. The object has a variety of properties and methods attached to it but we can also attach our own. This can be a useful way to keep track of data that needs to persist outside our function.** 
 + 
 +Maintenant que nous avons une référence au cercle, c'est une tâche très simple de paramétrer explicitement le style ou de modifier sa liste de classes. Voici la fonction buttonPressed() (ci-dessous) réécrite pour régler directement la couleur de remplissage du cercle. Notez que j'ai enlevé le « else », car nous voulons que le code échoue en silence sans effet colatéral si le sélecteur de CSS n'obtient aucune correspondance. 
 + 
 +En dépit de ce que j'ai dit précédemment, la méthode querySelector() ne retourne pas vraiment un nœud SVG, comme tel, mais plutôt un objet JavaScript qui fait référence à l'élément dans la structure interne du document du navigateur. En général, vous pouvez ignorer cette subtile distinction, mais ça signifie quand même que vous avez en main un objet JS qui nous offre quelques avantages quand nous écrivons notre code. L'objet a une palette de propriétés et de méthodes qui lui sont attachées, mais nous pouvons lui attacher les nôtres. Ce peut être une façon utile de garder une trace de données qui doivent persister en dehors de notre fonction. 
 + 
 +**Consider trying to toggle the color in response to the button presses. You could use a CSS class, and call the circle.classList.toggle() method to alternately add and remove it. This is similar to the approach we took last time, except we’re referencing our object variable rather than “this”. But what if you want to set the fill color on the circle directly, rather than via a class? You could read the value of circle.style.fill back, and test to see what it’s currently set to. But there are various ways to define colors in CSS, so you might not get back the format you expect. 
 + 
 +A better approach is to create a property on the object that you can refer to each time the function is called. You can test its current value, then set it to something else before your function finishes. You don’t need to do anything fancy to create a property like this – the browser will create it as soon as you try to use it – so the code ends up looking like that shown next page, bottom left.** 
 + 
 +Tentez un essai de changement de couleur en réponse à un appui sur le bouton. Vous pouvez utiliser une classe du CSS et appeler la méthode circle.classList.toggle() pour alternativement l'appliquer et l'enlever. C'est semblable à l'approche que nous avons prise la dernière fois, sauf que nous faisons référence à notre variable objet plutôt qu'à « this ». Mais que ce passe-t-il si nous réglons la couleur du cercle directement, plutôt que via une classe ? Vous pouvez relire la valeur de circle.style.fill et tester pour voir quel est actuellement le réglage. Mais il y a de nombreuses façons de définir des couleurs dans le CSS ; aussi, vous pourriez ne pas recevoir le format que vous attendez en retour.
  
-Now that we’ve got a reference to the circleit’s a pretty simple task to set the style explicitly, or modify its class listHere’s the buttonPressed() function (below) rewritten to directly set the fill color on the circle. Note that I’ve removed the “else”as we just want the code to fail silently with no side-effects if the CSS selector fails to match anything.+Une meilleure approche est de créer une propriété sur cet objet à laquelle vous pouvez vous référer chaque fois que la fonction est appelée. Vous pouvez tester sa valeur actuellepuis la régler à quelque chose d'autre avant que votre fonction finisseVous n'avez pas besoin d'imaginer quoi que ce soit de raffiné pour créer une propriété comme celle-cile navigateur la créera dès que vous essayerez de l'utiliser ; ainsi le code finit par ressembler à ce qui est montré à la page suivante, en bas à gauche.
  
-Despite what I said earlier, the querySelector() method doesn’t actually return the SVG node, as suchbut rather a JavaScript object that references the element in the browser’s internal document structure. Usually you can ignore this subtle distinctionbut it does mean that we have a JS object in handwhich offers us few advantages when writing our code. The object has a variety of properties and methods attached to it but we can also attach our ownThis can be a useful way to keep track of data that needs to persist outside our function.+**The first time you click the button the “isOn” property doesn’t exist. That means the test in the “if” statement failsand the code in the “else” runs – setting the color to greenand creating the “isOn” propertywith value of “true”. The next time you click the button the “if” succeeds, the fill is set to red and the property is set to “false”Thereafter the color and property will continue to toggle each time you click the button.
  
-Consider trying to toggle the color in response to the button presses. You could use CSS class, and call the circle.classList.toggle() method to alternately add and remove itThis is similar to the approach we took last timeexcept we’re referencing our object variable rather than “this”. But what if you want to set the fill color on the circle directly, rather than via a class? You could read the value of circle.style.fill back, and test to see what it’s currently set to. But there are various ways to define colors in CSSso you might not get back the format you expect.+One important thing to note as we’ve been editing this code is that you haven’t had to go anywhere near Inkscape since the initial setup. This is one big advantage of using external, linked scripts, as there’s less chance of accidentally making changes to your SVG file. You also get all the benefits of using proper text editor: with any half-decent editor you should get syntax highlighting and other aids, which can help to indicate problems in your codePlus, being able to work in a proper sized window, rather than the single line of the Object Properties dialog or the letterbox of Inkscape’s Embedded Scripts tabis a huge advantage.**
  
-A better approach is to create a property on the object that you can refer to each time the function is calledYou can test its current valuethen set it to something else before your function finishesYou don’t need to do anything fancy to create a property like this – the browser will create it as soon as you try to use it – so the code ends up looking like that shown next pagebottom left.+La première fois que vous cliquez sur le bouton, la propriété « isOn » n'existe pasÇa signifie que le test de la déclaration « if » échoueet le code de « else » s'exécute, réglant la couleur en vert et créant la propriété «isOn », avec la valeur « true » (vrai)La prochaine fois que vous cliquez sur le bouton, le « if » est un succès, le remplissage devient rouge et la propriété est mis à « false » (faux). Par la suitela couleur et la propriété continueront de permuter à chaque fois que vous cliquerez sur le bouton.
  
-The first time you click the button the “isOn” property doesn’t exist. That means the test in the “if” statement fails, and the code in the “else” runs – setting the color to greenand creating the “isOn” propertywith value of “true”The next time you click the button the “if” succeedsthe fill is set to red and the property is set to “false”Thereafter the color and property will continue to toggle each time you click the button.+Une chose importante à noter lors de la modification de ce code, c'est que vous n'avez pas eu à vous approcher d'Inkscape depuis le paramétrage initial. C'est un des gros avantages de l'utilisation des scripts externes liéscar il y moins de chances de faire des modifications accidentelles dans le fichier SVGVous avez aussi tous les bénéfices de l'utilisation d'un éditeur de texte adapté : avec un éditeur à moitié convenablevous aurez la mise en valeur de la syntaxe et d'autres aides, ce qui peut aider à signaler des problèmes dans votre codeEn plus, en étant capable de travailler dans une fenêtre de taille correcte, plutôt que sur l'unique ligne du dialogue des Propriétés de l'objet ou le petit cadre de l'onglet Scripts incorporés d'Inkscape, vous disposez d'un énorme avantage.
  
-One important thing to note as we’ve been editing this code is that you haven’t had to go anywhere near Inkscape since the initial setup. This is one big advantage of using external, linked scripts, as there’s less chance of accidentally making changes to your SVG file. You also get all the benefits of using a proper text editor: with any half-decent editor you should get syntax highlighting and other aids, which can help to indicate problems in your codePlusbeing able to work in proper sized window, rather than the single line of the Object Properties dialog or the letterbox of Inkscape’s Embedded Scripts tab, is a huge advantage.+**When deploying an SVG file with a linked script, you need to make sure that the script is still accessible to the SVG file once it’s on to your web server – typically by ensuring you use a relative path as outlined at the top of this article. You have to make sure you remember to keep your JS file in sync with any changes to your SVG file or its locationBut this additional housekeeping is usually more than worth it. Generallyunless you really are writing only a single line of code, or perhaps a singleshort function, linking is the way to go.**
  
-When deploying an SVG file with a linked script, you need to make sure that the script is still accessible to the SVG file once it’s on to your web server – typically by ensuring you use a relative path as outlined at the top of this article. You have to make sure you remember to keep your JS file in sync with any changes to your SVG file or its locationBut this additional housekeeping is usually more than worth itGenerallyunless you really are writing only a single line of code, or perhaps a single, short functionlinking is the way to go.+Lors du déploiement d'un fichier SVG avec un script liévous devez vous assurer que le script reste accessible au fichier SVG une fois qu'il est chargé dans votre navigateur Web, typiquement en vous assurant que vous utilisez un chemin relatif comme souligné au début de cet article. Assurez-vous de vous souvenir de garder votre fichier JS synchronisé avec tous les changements dans votre fichier SVG ou de sa localisationMais cette maintenance supplémentaire vaut en général largement le coupDans l'ensemblesauf si vous n'écrivez réellement qu'une seule ligne de code, ou peut-être une seule et courte fonctionle lien est la bonne manière de faire
  
issue146/inkscape.1562059497.txt.gz · Dernière modification : 2019/07/02 11:24 de auntiee