Commande SVG

Commande SVG

Ph.Leroy

2018-09-27

SVG

SVG est un langage de tracé de graphique vectoriel. Ce mémo est juste un pense-bête minimaliste. Pour tout savoir

Commandes

Commande Syntaxe Commentaire
Fichier svg <svg xmlns="..." x= "" y="" width="" height=""> </svg> Dans un fichier .svg, on définit la largeur et la hauteur du svg
Dans un fichier html <svg width="" height="" viewBox="0 0 256 256"> ...</svg> Inclus directement dans un fichier html
Dans un fichier css background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='256' height='256' viewBox='0 0 256 256'%3E%3Cpath d='M201.5 24v31.4h31.7V234H55.5v-30H22.7V24h178.8zm-11.8 11.4H34.4v157.3h155.2V35.4z'/%3E%3C/svg%3E"); à noter que < est remplacé par %3C, > %3E, # par %23 et " par '
Vue <svg viewbox="x0 y0 w0 h0"></svg> Définit la vue, en particulier attention au dépassement du cadre
Rapport Largeur Hauteur <svg preserveAspectRatio = { none, xMidYMid, xMinYMin, xMaxYMax} > </svg> Precise comment évolue au redimensionnement: rempli tout, uniforme sur le centre, uniforme sur le csg, uniforme sur le cid

Formes

Commande Syntaxe Commentaire
cercle <circle cx="40" cy="62" r="8" stroke="none" stroke-width="0" fill="rgb( 255, 0, 0)"/>
ellipse <ellipse cx="" cy="" rc="" ry="" />
rectangle <rect x="" y="" width="" height="" rx="" ry="" /> rx et ry pour l'arrondi des coins
polygone <polygon points="x0,y0 x1,y1 x2,y2" />
ligne <line x1="" y1="" x2="" y2="" />
polyligne <polyline points="x0,y0 x1,y1 x2,y2" />
chemin <path d="M100,160 Q128,190 156, 160" /> cf. Commandes de chemins
texte <text font-size="12" x="102" y="55" id="text7074" style="font-size:12px;font-family:Verdana;fill:#000000;stroke:none">Mon texte</text> cf. Texte

Transformations

On peut appliquer des tranformations aux éléments avec l'attribut transform; par exemple <rect x="10" y="20" width="height" height="50" transform="rotate(45)" />.

Commande Syntaxe Description
translation translate( x, y) translation relative
rotation rotate( angle) rotation autour du point (0,0) d'un angle en degré
rotation rotate( angle, x, y) rotation autour du point (x,y) d'un angle en degré
Mise à l'échelle scale( ratio) Mise à l'échelle des dimensions mais aussi des abscisses et ordonnées
+ scale( rx, ry) Mise à l'échelle différencièe sur x et y
+ scale( -1, 1) Effet miroir sur l'axe des x
Biais skewX(angle) ou skewY(angle) Applique un biais défini par un angle en degré sur l'un des axes
Transformée matricielle matrix( a, b, c, d, e, f) Utilisant des matrices homogènes [ [a,c,e], [b,d,f], [0,0,1]]
+ translation matrix( 1,0,0,1,tx,ty) translation
+ rotation matrix( cos(a), sin(a), -sin(a), cos(a), 0, 0) rotation
+ échelle matrix( sx, 0, 0, sy, 0, 0) Biais

Les transformations peuvent être combinées au sein d'un seul attribut ```<rect x="50" y="10" width="20" height="30" style="stroke: #000000; fill:none;" transform="translate(50,0) rotate(30)" />``` Les opérateurs sont appliqués de la gauche vers la droite.

Commandes de chemins

Les (, ) et + sont des précisions de la syntaxe, il ne sont pas dans le chemin.

Commande Syntaxe Description
Move M (x,y)+ Déplacement aux coordonnées absolues
move m (dx,dy)+ Déplacement relatif
LineTo L (x,y)+ Tracé d'une ligne du point courant aux coordonnées absolues
Horizontal line H x+ Tracé d'une ligne horizontale du point courant au point d’abscisse x
horizontal line h dx+ Idemen en relatif
Vertical line V y+ Tracé d'une ligne verticale du point courant au point d’ordonnée y
vertical line h dx+ Idem en relatif
Cubique de Bézier C (x1,y1,x2,y2,x,y)+ Dessine un bézier du point courant au point final x,y, le point de controle initial est x1,y1 et final est x2,y2. Tous les triplets de coordonnées successifs sont considérés comme des cubiques
cubique de Bézier c (dx1,dy1,dx2,dy2,dx,dy)+ Idem mais les coordonnées précisé sont relatives au point courant
Quadratique de Bézier S (x2,y2,x,y)+ Dessine un bézier du point courant au point final x,y, le point de controle final est x2,y2, le point de controle intial est le symétrique du point de controle final du segment précédent, si le segment précédent n'était pas un courbe le point de controle initial est identique au point de contrôle initial (courant); Toutes les paires de coordonnées successifs sont considérées comme des quadratiques.
quadratique de Bézier c (dx2,dy2,dx,dy)+ Idem mais les coordonnées précisées sont relatives au point courant
arc elliptic a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Tracé d'un arc elliptique du point courant au point x,y, de rayon rx et ry, tourné de x-axis-orientation. Le centre de l'ellipse cx,cy est calcule automatiquement. Large-arc-flage (0 ou 1) et sweep-lag (0 ou 1) permettent de choisir le grand arc (1) par rapport à nos deux points (origine et fin) et le sens de balayage (il faut essayer pour comprendre).
+ A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ idem en déplacement absolu

Regrouper et nommer

Commande Syntaxe Description
Grouper des éléments <g> items </g> Regroupe des éléments pour leurs appliquer des transformations communes
Classes <elem class="MaClasse">..</elem> L'attribut de classe peut etre associe a tout élément
Identifiants <elem id="MonId" > ... </elem> L'attribut ID peut etre rajouté à tout éléménet
Symbol <symbol id="MyIcon" viewBox="x0 y0 w0 h0"> ... </symbol> Pour créer des éléments graphiques réutilisables, comme des icones
Instanciation de symbole <use href="#MyIcon" /> on peut utiliser nos symboles enregistrés
Definitions <defs> <path id="arc" d="M100,160 Q10,20 30,40" /> ... </defs> Déclaration de formes et de grapjhiques avant leur utilisation

Décoration des formes

Commande Syntaxe Description
Fill <elem fill="couleur" /> Définit la couleur de remplissage mot-clé, #hex, rgb(),rgba()
Opacity <elem opacity=".5" fill="orange" ... />
Gradients <defs> <linearGradient id="grd0"> <stop offset="0%" stop-color="orange" /> <stop offset="100%" stop-color="red" /> </linearGradient></defs>
- <circle fill="url(#grd0)" cx="100" cy="100" r="10" /> Voila un cercle en couleur dégradée
Stroke <elem stroke="clr" ... /> ajoute un bord à la forme
stroke width <elem stroke-width="3" ... /> l'épaisseur du bord
stroke opacity <elem stroke-opacity="0.4" ... /> l'épaisseur du bord
stroke linecap <elem stroke-linecap="round" ... /> le bout des bords { butt, round, square }
stroke linejoin <elem stroke-linejoin="miter" ... /> la jonction des traits { miter, round, bevel}
stroke miterlimit <elem stroke-miterlimit="4" ... /> la jonction de deux coins
line dashes <line stroke-dasharray="4,6" ... /> les tirets

Accessibilité

Commande Syntaxe Description
titre <title>Mon titre</title> Texte de remplacement du dessin en cas impossibilité d'affichage
description <desc>bla bla</desc> Description détaillée du dessins, par exemple tous les points d'une courbe
masquage <svg aria-hidden="true">...</svg> Les outlis d'accessibilité (braille par exemple) peuvent complétement sauter l'affichage du svg
complément d'acceesibilité <svg aria-details="#mes-infos">...</svg> On fait référence à un élément html
+ <div id="mes-infos"><h2>Incroyable</h2><p>Je n'ai rien à déclarer</p></div> qui est déclaré ainsi

Texte

Commande Syntaxe Description
Font family <text font-family="Georgia, serif">Voila!</text> { Sans-serif, Serif, Monospace , Cursive , Fantasy }
Font size <text font-size="1.5rem">Voila!</text>
Font weight <text font-weight="bold">Voila!</text>
Font style <text font-style="italic">Voila!</text>
Text decoration <text text-decoration="none">Voila!</text>
Letter spacing <text letter-spacing="30">Voila!</text>
Text length <text textLength="900">Dinosaurs!</text> Space out the letters to fill a specific width.
Text blocks <text x="" y="" text-anchor="middle"> Voila!</text> Ancre le texte sur ce point, le point de référence dans le texte est soit à gauche (start), au centre (middle) ou à droite (stop)
Mise en valeur dans le texte <text x="" y=""> Je dis <tspan fill="red"> une </tspan> chose</text> Le mot "une" est mis en valeur dans le texte
Text adjustements <text x="" y=""> Je dis <tspan dy="-30"> une </tspan> chose</text> Le mot "une" est remonté de 30pixels.
Texte sur un chemin <defs><path id="arc" d="M100,160 Q128,190 156,160" /></defs> Définissons un chemin
+ <textPath href="#arc">Voila!</textPath> Avant il fallait écrire xlink:href= ...
Gradients <defs> <linearGradient id="ce-gradient"> <stop offset="0%" stop-color="limegreen" /> <stop offset="100%" stop-color="green" /> </linearGradient></defs> Comme avec les gradients de forme on définit un greadient
+ <text fill="url(#ce-gradient)">VOila!</text> et on le référence
Web font <link href="http://fonts.googleapis.com/css?family=Denk+One" rel="stylesheet"> Incorporons la fonte que l'on veut utiliser
+ <text font-family="Denk One" x="10" y="100">Voila!</text> et on la référence
Web font avec le css <style> text { font-family: "Denk One";}</style> Identifions la fonte
+ <text x="10" y="100">Voila!</text> et on la référence automatiquement

Fontes

Fonte
Calibri, sans-serif
Arial, Helvetica, sans-serif
swiss, sans-serif
DejaVu Sans, sans-serif
Garamond, serif
'Times New Roman', Times, serif
DejaVu Serif, serif
Georgia, serif
modern, monospace
'Courier New', Courier, modern, monospace
script, cursive
'Comic Sans MS', 'Comic Sans', 'Lucida Handwriting', script, cursive
decorative, fantasy
Fraktur, fantasy

Liens & images

Liens

Commande Syntaxe Description
Lien <a href="https://fr.wikipedia.org/wiki/Sp%C3%A9cial:Page_au_hasard"> <text>Voila!</text></a> C''est le lien a du html (avant on avait xlink:href=)

Images

Commande Syntaxe Description
Image <image width="500" height="500" href="image/moi.jpg" /> Même chose qu'en html (avant on avait xlink:href=)

Présentation avec les CSS

Mise en valeur des formes (Styling shapes)

Un grand nombre d'attribut de mise en valeur définis ci-dessus peuvent être définis en CSS.

        <circle class="face" cx="128" cy="128" r="120" />

        .face {
          fill: yellow;
          stroke: #000;
          stroke-width: 6px;
          stroke-dasharray: 4,4;
        }

Mise en valeur du texte

Un grand nombre d'attribut de mise en valeur de texte définis ci-dessus peuvent être définis en CSS.

        <text class="dinos">Dinosaurs!</text>

        .dinos {
          font-family: Georgia, serif;
          font-style: italic;
          font-size: 1.5rem;
        }

Styling effects

Many of the effect related attributes can also be styled in CSS.

<rect class="box" x="0" y="0" width="256" height="64" />

.box { fill: limegreen; transform: rotate(45deg); transition: all .25s linear; }

.box:hover { fill: orange; }

Effects

Hover

Using CSS we can add hover effects to any SVG element.

Only works if the SVG is embedded in the HTML.

<rect class="box" x="0" y="0" width="256" height="64" />

.box { fill: green; }

.box:hover { fill: limegreen; }

Transformations

The transform property in CSS actually started in SVG, so it’s an attribute or CSS.

<rect transform="rotate(45)" x="0" y="0" width="256" height="64" />

Or in CSS:

rect { transform: rotate(90deg); }

Transform origin

In SVG, the transform origin for rotation is set in the rotate() value.

<rect transform="rotate(45, 10, 10)" x="0" y="0" width="256" height="64" />

In CSS, we can use transform-origin—but we cannot use the keywords like center, it has to be set in pixels.

rect { transform: rotate(90deg); /* These pixels are within the SVGs viewport pixel measurements */ transform-origin: 10px 10px; }

Transitions

Using CSS we can add transitions to any SVG element.

Only works if the SVG is embedded in the HTML.

<rect class="box" x="0" y="0" width="256" height="64" />

.box { fill: green; transition: all .25s linear; }

.box:hover { fill: limegreen; }

Animations

Using CSS we can add animations to any SVG element.

Only works if the SVG is embedded in the HTML.

<rect class="box" x="0" y="0" width="256" height="64" />

.box { animation: spin 2s linear; }

@keyframes spin {

0% { transform: rotate(0); }

100% { transform: rotate(360deg); }

}

Masking

Making parts of graphics and text semi-transparent with masks.

<defs> <mask id="mask"> <image width="500" height="200" xlink:href="images/text-mask.png" /> </mask> </defs>

<rect mask="url(#mask)" x="0" y="0" width="256" height="64" /> <text mask="url(#mask)">Splatter!</text>

The <mask> element inside of the definitions can be used along with the mask="" attribute.

Mask should be black and white images: the black becoming transparent & the white showing.

Texturing & patterns

Filling inside graphics and text with a repeating texture or pattern.

<defs> <pattern width="500" patternUnits="userSpaceOnUse" height="200" id="texture"> <image xlink:href="images/mars.jpg" width="800" height="500" /> </pattern> </defs>

<rect fill="url(#texture)" x="0" y="0" width="256" height="64" /> <text fill="url(#texture)">Mars</text>

The <pattern> element inside of the definitions can be used along with the fill="" attribute.

Filters

Filters allow graphic effects to be applied to elements and text.

<defs> <filter id="blur-me"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> </defs>

<rect filter="url(#blur-me)" x="0" y="0" width="256" height="64" /> <text filter="url(#blur-me)">Mars</text>

SVG icons

Spritebot

Drop a bunch of exported icons from Illustrator into Spritebot and save.

Put the saved sprite sheet into your images folder.

The original, exported SVGs can be trashed.

Using icons

Use the <svg> tag and the <use> tag to grab an icon from within the sprite sheet.

The id of the icon is the same as it’s filename when dropped into Spritebot.

<svg><use xlink:href="images/icons.svg#stego"></use></svg>

It’s usually a good thing to insert it into an element for CSS control.

<i class="icon i-32"> <svg><use xlink:href="images/icons.svg#stego"></use></svg> </i>

Seeing icons

SVG icons won’t load in Chrome, Firefox or Opera if you double click the HTML file.

They will still absolutely work in those browsers when your website is online.

This is a security feature of the browsers.

They will load properly in Safari.

To get proper loading on the local version you need a web server—drop your folder into Markbot and press ⌘B

Accessibility

Titles & descriptions

<title>Dinosaurs are among us!</title>

Use the <title> tag to add alternative text to an SVG—think of it like the <img alt="">

<desc>Dinosaurs are living among us now—or at least their descendants—in the form of birds.</desc>

The <desc> tag is for more complex descriptions and information.

If the SVG was a pie-chart, for example, <desc> would hold all the percentages and stuff.

ARIA descriptions

<svg aria-details="#dino-info"></svg>

<div id="dino-info"> <h2>Dinosaurs are among us!</h2> <p>Dinosaurs are living among us now—or at least their descendants—in the form of birds.</p> </div>

The aria-details attribute is a great way to use HTML to complement an SVG—especially if the content is really detailed.

Hiding SVGs

        <svg aria-hidden="true">
          <text>Juste pour la décoration!</text>
        </svg>

The aria-hidden="true" attribute can be used to completely hide the graphic and its text from accessibility tools. L'attribut aria-hidden="true" permet de ne pas polluer la lecture d'une page par un lecteur spécifique pour une personne handicapé, avec des informations accessoires. ARIA signifie "Application Internet Enrichie pour Handicapés ("Accessible Rich Internet Applications").

Donc si on veut être attentifs aux personnes qui naviguent sans voir les images mais seulement avec un générateur vocal, on soustrait les commandes graphiques de la lecture. C'est important!