问题
I have quite a few SVG icons saved in different *.svg files. If I insert them into the page directly I can freely control their colors with the fill css option.
My trouble comes that I need to change the color of the svg and then display it in an img tag, because an important for the project library can only work with that. Is there a solution to my predicament?
I need to be able to change the color of the svg and receive similar or the same end result. Is this even possible?
EDIT
Is it possible to include javascript in the svg file that will read parameters and change color accordingly? For example:
I am not sure how can this be achieved.
解决方法
You can pass your svg doc as a dataURL :
So, either you download the file through xhr, append it to an svg element and then convert it to this dataURL,
var parser = new DOMParser();
var svgDoc = parser.parseFromString(xhr.response, "image/svg+xml");
svgDoc.querySelector('#yourElement').setAttributeNS(null, 'fill', yourColor);
var dataURL = encodeURIComponent(new XMLSerializer().serializeToString(svgDoc));
img.src = dataURL;
or you load it through an or an element and then convert its contentDocument :
var obj = document.createElement('object');
obj.src = "path/to/your/file.svg";
obj.onload = function(){
var svgDoc = obj.contentDocument;
svgDoc.querySelector('#yourElement').setAttributeNS(null, 'fill', yourColor);
var dataURL = encodeURIComponent(new XMLSerializer().serializeToString(svgDoc));
img.src = dataURL;
}
Of course, these solutions are limited by the cross-origin policies.