Question:
I'm adding an svg image to HTML markup using the <img>
.
The image is black and white. It is necessary to paint over it, for example, in blue or green.
Applying CSS rules to svg fill
, stroke
does not give the desired effect.
.img1 {
fill:dodgerblue;
stroke:white;
path:inherit;
stroke:inherit;
width:30vw;
height:30vh;
}
</style>
<img class="img1" src="https://image.flaticon.com/icons/svg/181/181549.svg">
Are there other ways to get the desired result?
Answer:
There is another way. For all img elements with svg in the markup, add the .svg class, then select and replace them with svg using Javascript.
Doesn't work in IE11, Opera Mini
document.querySelectorAll('img.svg').forEach(img => {
var imgId = img.id;
var imgClass = img.className;
var imgURL = img.src;
var imgFill = img.getAttribute('data-fill');
fetch(imgURL).then(r => r.text()).then(text => {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
var svg = xmlDoc.getElementsByTagName('svg')[0];
if (typeof imgId !== 'undefined') {
svg.setAttribute('id', imgId);
}
if (typeof imgClass !== 'undefined') {
svg.setAttribute('class', imgClass);
}
if (typeof imgFill !== 'undefined') {
svg.setAttribute('fill', imgFill);
}
img.parentNode.replaceChild(svg, img);
}).catch(console.error);
});
.svg {
width:25px;
height:25px;
-webkit-transition: fill 280ms ease;
-moz-transition: fill 280ms ease;
-ms-transition: fill 280ms ease;
-o-transition: fill 280ms ease;
transition: fill 280ms ease;
}
.svg:hover {
fill: green;
cursor: pointer;
}
#test2 {
fill:orange;
}
#test2:hover {
fill:purple;
}
<img class="svg test1" data-fill="blue" src="https://image.flaticon.com/icons/svg/32/32441.svg">
<img class="svg test2" id="test2" src="https://image.flaticon.com/icons/svg/181/181549.svg">
<img class="svg test3" src="https://image.flaticon.com/icons/svg/181/181549.svg">