Intégration web angularforall.com

- SVG inline HTML : animations et interactivité

Svg Vectoriel Html5 Animations Interactivité Graphics Responsive
SVG inline HTML : animations et interactivité

Maîtrisez SVG inline dans HTML pour créer des graphiques vectoriels scalables, animables et interactifs. 12+ exemples avec CSS et JavaScript.

SVG : avantages et use-cases

SVG (Scalable Vector Graphics) permet de créer des graphiques qui s'adaptent parfaitement à n'importe quel écran, sans pixellisation. Contrairement aux images raster, les SVG sont vectoriels et infiniment scalables.

Découvrez comment intégrer du SVG directement dans votre HTML, l'animer avec CSS et JavaScript, et créer des interfaces interactives et modernes.

Avantages du SVG :

  • Scalable : parfait sur tous les appareils, du mobile au 4K
  • Léger : format texte, petite taille de fichier
  • Stylisable : CSS et JavaScript peuvent modifier l'apparence
  • Accessible : texte intégré, attributs ARIA supportés
  • Animable : CSS animations, transitions, SMIL, GSAP
  • Interactif : events, hover states, user interactions

Quand utiliser SVG :

  • Logos, icônes, illustrations
  • Graphiques et data visualisations
  • Animations interactives
  • Interfaces responsives

Syntaxe de base et éléments

Formes de base

<!-- Rectangle -->
<rect x="10" y="10" width="100" height="50" fill="blue" stroke="black" stroke-width="2"/>

<!-- Cercle -->
<circle cx="100" cy="100" r="50" fill="green"/>

<!-- Ellipse -->
<ellipse cx="100" cy="100" rx="50" ry="30" fill="red"/>

<!-- Ligne -->
<line x1="0" y1="0" x2="200" y2="200" stroke="black" stroke-width="2"/>

<!-- Poly-ligne -->
<polyline points="10,10 20,20 30,30 40,20 50,10" fill="none" stroke="blue"/>

<!-- Polygone (fermé) -->
<polygon points="50,10 90,90 10,90" fill="purple"/>

<!-- Texte -->
<text x="50" y="50" font-size="24" fill="black">Hello SVG</text>

Chemins (paths)

<!-- Chemin : M=moveTo, L=lineTo, C=cubicBezier, Z=closePath -->
<path d="M 10 10 L 100 10 L 100 100 L 10 100 Z" fill="yellow" stroke="black"/>

<!-- Courbe lisse (Bézier) -->
<path d="M 10 80 Q 95 10 180 80" stroke="blue" fill="none" stroke-width="2"/>

SVG inline dans le HTML

Structure basique

<!-- SVG inline -->
<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="80" fill="lightblue" stroke="navy" stroke-width="2"/>
    <text x="100" y="105" text-anchor="middle" font-size="20" fill="navy">
        SVG
    </text>
</svg>

Attributs importants :

  • viewBox="x y width height" : système de coordonnées interne (plus important que width/height pour le responsive)
  • xmlns : namespace XML (obligatoire pour SVG valide)
  • preserveAspectRatio : comment étirer/adapter le viewBox

SVG responsive

<!-- Utiliser viewBox sans width/height pour responsive -->
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"
     style="width: 100%; max-width: 300px; height: auto;">
    <rect width="200" height="200" fill="lightblue"/>
    <circle cx="100" cy="100" r="50" fill="orange"/>
</svg>

Animations CSS sur SVG

Animations simples

<style>
    .circle-animate {
        animation: spin 3s linear infinite;
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
</style>

<svg viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="blue" class="circle-animate"/>
</svg>

Animer les propriétés SVG

<style>
    .stroke-animate {
        animation: strokeDash 2s ease-in-out infinite;
        stroke-dasharray: 100;
        stroke-dashoffset: 100;
    }

    @keyframes strokeDash {
        0% {
            stroke-dashoffset: 100;
        }
        50% {
            stroke-dashoffset: 0;
        }
        100% {
            stroke-dashoffset: -100;
        }
    }
</style>

<svg viewBox="0 0 100 100">
    <path d="M 10 50 Q 50 10 90 50"
          stroke="red" stroke-width="2" fill="none"
          class="stroke-animate"/>
</svg>

Interactivité avec JavaScript

Événements SVG

<svg id="clickableSvg" viewBox="0 0 100 100">
    <rect id="myRect" x="10" y="10" width="80" height="80" fill="blue"/>
</svg>

<script>
const rect = document.getElementById('myRect');

// Survol
rect.addEventListener('mouseenter', () => {
    rect.setAttribute('fill', 'red');
});

rect.addEventListener('mouseleave', () => {
    rect.setAttribute('fill', 'blue');
});

// Clic
rect.addEventListener('click', () => {
    rect.setAttribute('r', 50); // Change dynamiquement
    console.log('Rectangle cliqué !');
});
</script>

Animations JavaScript avec style

// Changer les styles SVG
const circle = document.querySelector('circle');

circle.addEventListener('click', function() {
    this.style.fill = 'orange';
    this.style.transition = 'fill 0.3s ease';
});

// Ou avec setAttribute pour les attributs SVG spécifiques
circle.setAttribute('cx', 150);
circle.setAttribute('r', 30);

Transformations et filtres

Transformations basiques

<svg viewBox="0 0 200 200">
    <!-- Rotation -->
    <rect x="75" y="75" width="50" height="50" fill="blue" transform="rotate(45 100 100)"/>

    <!-- Mise à l'échelle -->
    <circle cx="100" cy="100" r="30" fill="green" transform="scale(2)"/>

    <!-- Translation -->
    <polygon points="0,0 50,0 25,50" fill="red" transform="translate(100 100)"/>
</svg>

Filtres visuels

<svg viewBox="0 0 200 200">
    <defs>
        <!-- Définir un filtre de flou -->
        <filter id="blur">
            <feGaussianBlur stdDeviation="5"/>
        </filter>

        <!-- Ombre -->
        <filter id="shadow">
            <feGaussianBlur in="SourceAlpha" stdDeviation="3"/>
            <feOffset dx="2" dy="2" result="offsetblur"/>
            <feComponentTransfer>
                <feFuncA type="linear" slope="0.5"/>
            </feComponentTransfer>
            <feMerge>
                <feMergeNode/>
                <feMergeNode in="SourceGraphic"/>
            </feMerge>
        </filter>
    </defs>

    <circle cx="50" cy="50" r="30" fill="blue" filter="url(#shadow)"/>
    <circle cx="150" cy="150" r="30" fill="green" filter="url(#blur)"/>
</svg>

Performance et optimisations

Minification SVG

Utilisez SVGO pour minifier les SVG :

npm install -g svgo
svgo mon-image.svg  # Crée mon-image.optimized.svg

Caching et réutilisabilité

<!-- Définir une forme réutilisable -->
<svg viewBox="0 0 200 200">
    <defs>
        <g id="icon-star">
            <polygon points="50,10 61,40 90,40 67,60 78,90 50,70 22,90 33,60 10,40 39,40"/>
        </g>
    </defs>

    <!-- Utiliser plusieurs fois -->
    <use href="#icon-star" x="0" y="0" fill="gold"/>
    <use href="#icon-star" x="100" y="0" fill="silver"/>
</svg>

Conclusion

SVG maîtrisé : Vous savez créer des graphiques scalables, animables et interactifs sans dépendre d'images raster.

Bibliothèques utiles pour SVG :

  • GSAP : animations fluides et complexes
  • SVG.js : API simplifiée pour manipuler SVG
  • SVG Repo : base de SVG gratuits

Partager