SVG-Bilder sind eine tolle Sache – besonders wenn man sie auf Webseiten einbindet: Die Speichergröße ist gering, die Images sind ohne Qualitätsverlust skalierbar und sogar der Internet Explorer 9 kann damit etwas anfangen. Im Gegensatz zu herkömmlichen Bildformaten, haben sie aber noch einen Vorteil: Mit CSS kann ihre Farbe verändert und auf Wunsch sogar animiert werden.
Das Markup
[html]<img src="logo.svg" class="svg" id="logo" />[/html]
Vorbereitung mit JavaScript
Zuerst muss via jQuery der Inhalt der .svg-Bilddatei in den Image-Tag eingefügt werden. Dies kann natürlich auch direkt im Markup erledigt werden. Beide Methoden haben Vor- und Nachteile.
[js]
$(‚img.svg‘).each(function(){
var $img = $(this),
imgID = $img.attr(‚id‘),
imgClass = $img.attr(‚class‘),
imgURL = $img.attr(’src‘);
$.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = $(data).find(’svg‘);
// Add replaced image’s ID to the new SVG
if(typeof imgID !== ‚undefined‘) {
$svg = $svg.attr(‚id‘, imgID);
}
// Add replaced image’s classes to the new SVG
if(typeof imgClass !== ‚undefined‘) {
$svg = $svg.attr(‚class‘, imgClass+‘ replaced-svg‘);
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr(‚xmlns:a‘);
// Replace image with new SVG
$img.replaceWith($svg);
});
});
[/js]
Quelle: stackoverflow.com
Farbe des Bildes ändern
Nun kann direkt via CSS die Farbe des SVG-Bildes angepasst werden:
[css]#logo path {color: red}[/css]
Farbe animieren
Natürlich ist es jetzt auch möglich den gewünschten Farbwert via Animation zu verändern. Im folgenden Beispiel passiert das bei Mouse-Hover:
[css]#logo path {
-webkit-transition: all 1;
-moz-transition: all 1;
-ms-transition: all 1;
-o-transition: all 1;
transition: all 1;
}
#logo:hover path {color: green}
[/css]
Das ganze funktioniert in allen Browsern die mit SVG-Bildern und CSS3-Transitions etwas anfangen können.