If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG.
However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.
Built off the above but with dynamic creation and a vector image, not drawing.
function svgztruck() {
tok = "{d path value}"
return tok;
}
function buildsvg( eid ) {
console.log("building");
var zvg = "svg" + eid;
var vvg = eval( zvg );
var raw = vvg();
var svg = document.getElementById( eid );
svg.setAttributeNS(null,"d", raw );
svg.setAttributeNS(null,"fill","green");
svg.setAttributeNS(null,"onlick", eid + ".style.fill=#FF0000");
return;
}
You could call with:
<img src="" onerror="buildscript">
Now you can add colors by sub element and manipulate all elements of the dom directly. It is important to implement your viewbox and height width first on the svg html, not done in the example above.
There is no need to make your code 10 pages when it could be one... but who am I to argue. Better use PHP while your at it.
The inner element that svg builds on is a simple <svg lamencoding id=parenteid><path id=eid><svg> with nothing else.
Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.
There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.
After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.
I am probably replying way too late, but this is how I did it!
There is so many ways you can play with the color I was actually getting the rgba from a pixel using canvas and changing it dinamically, but for this example I am just going to use ramdon colors for the rgba, also you can use whatever you want, it does not have to be an rgba
Btw I am using uuid just to change the name dinamically every time a save an svg so it does not overwrite the original, but is not needed if you only want to use the code once I guess. Also remember that not all svg images have the property "stroke" or "fill" which is usually located in a style or a <path></path> so you need to play a little bit with that part, when the property is missing I usually just add it manually according to the color or colors of the svg for example if its black I just add fill="rgba(0,0,0,1)" or stroke="rgba(0,0,0,1)" or some times both depending on the svg
//Inside svg
<g id="#svgColor">
<path fill="rgba(0,0,0,1)".........lots of codes />
<path fill="rgba(0,0,0,1)".........lots of codes />
<path fill="rgba(0,0,0,1)".........lots of codes />
</g>
Logic Part
//svgColor.js
const fs = require("fs");
const path = require("path");
const uuid = require("uuid");
const changeSvgColor = () => {
try {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var a = Math.floor(Math.random() * 255);
const svgCode = fs.readFileSync(
path.resolve(__dirname, "./assets/watermark.svg"),
"utf8"
);
coloredSvgXml = svgCode.replaceAll(
"rgba(0,0,0,1)",
`rgba(${r},${g},${b},${a})`
);
fs.writeFile(
`./myFolder/assets/${uuid.v4()}.svg`,
coloredSvgXml,
function (err) {
console.log(err);
}
);
} catch (error) {
console.log(error);
}
};
module.exports = {
changeSvgColor,
};
After this then just go and create an index.js file (if you want),call your function and you should be ready to go :D
I know this is a pretty old question. But I stumbled over it searching for the same topic. Out of this and some other answers I finally built a function for precisely this topic:
It loads a SVG completely in JavaScript ...
removes the size-tags to make it scale with its parent DIV
even adjusts the viewbox to make it square and
changes the fillColor in different ways.
Maybe this is of help for some of you:
/* inspired by https://codepen.io/osublake/pen/OMRdKq */
function loadSvgIntoDiv(theDIV, pathToSvg, prefix = 'myPrefix-', fillColor = null, fillColorID = null)
{
if ( theDIV == null || typeof theDIV.appendChild != 'function' ) return null;
fetch(pathToSvg).then( (res) => {
// check the status
if (!res.ok)
{
switch (res.status)
{
case 404:
throw new Error('"' + pathToSvg + '" not found (error 404).');
default:
throw new Error('Failed to fetch "' + pathToSvg + '": ' + res.status + ' (' + res.statusText + ')');
}
}
let contentType = res.headers.get('content-type');
if ( typeof contentType == 'string' && contentType.indexOf('image/svg') !== -1 )
{
// hand over SVG-content to next .then
return res.text();
} else {
throw new Error('Unexpected content type (' + iconPath + ', ' + contentType + ')');
}
})
.then( (iconData) => {
// clean up SVG
// remove width and height from <svg ...>-tag to allow scaling
iconData = iconData.replace(/\<svg([^>]*)\>/ig, (match) => {
return match.replace(/width\=[\'\"]([^\"^\']*)[\"\']/ig, '').replace(/height\=[\'\"]([^\"^\']*)[\"\']/ig, '');
});
// adjust viewbox to be a square image
iconData = iconData.replace(/\<svg([^>]*)\>/ig, (match) => {
return match.replace(/viewbox\=[\'\"][^0-9^\.^\-]*([0-9\.\-]*)[^0-9^\.^\-]*([0-9\.\-]*)[^0-9^\.^\-]*([0-9\.\-]*)[^0-9^\.^\-]*([0-9\.\-]*)[^\"^\']*[\"\']/ig, (match, x, y, w, h) => {
x = Number(x);
y = Number(y);
w = Number(w);
h = Number(h);
if ( w < h ) { x=x-(h-w)/2; w=h; }
if ( h < w ) { y=y-(w-h)/2; h=w; }
return 'viewbox="' + x + ' ' + y + ' ' + w + ' ' + h + '"';
});
});
let origIcon = iconData;
// add fill-style to a given id
if ( fillColorID != null && fillColor != null )
{
let search = '/id\=[\"\']' + fillColorID + '[\"\']/ig';
iconData = iconData.replace(search, 'id="' + fillColorID + '" style="fill: ' + fillColor + '" ');
}
// edit all fill-statements within path-tags
if ( fillColor != null ) fillColor='fill="' + fillColor + '"';
if ( fillColor == null || fillColorID != null ) fillColor='';
iconData = iconData.replace(/\<path([^>]*)\>/ig, (match) => {
return match.replace(/fill\=[\'\"]([^\"^\']*)[\"\']/ig, fillColor);
});
iconData = iconData.replace(/\<g\ ([^>]*)\>/ig, (match) => {
return match.replace(/fill\=[\'\"]([^\"^\']*)[\"\']/ig, fillColor);
});
// no fill was added, as nothing was changed
if ( iconData == origIcon)
{
iconData = iconData.replace(/\<g\ ([^>]*)\>/ig, (match, p) => {
return '<g ' + replaceFill + p + '>';
});
iconData = iconData.replace(/\<path([^>]*)\>/ig, (match, p) => {
return '<path ' + replaceFill + p + '>';
});
}
// add prefix in front of every ID to prevent duplicates
iconData = iconData.replace(/id\=[\"\']([^\"^\']*)[\"\']/ig, 'id="' + prefix + '$1"');
// finally add the SVG to the div
theDIV.innerHTML = iconData;
})
.catch( (error) => {
// handle error messages
});
}