Home > Software design >  SVG change dynamic color
SVG change dynamic color

Time:04-28

I have svg images in menu list but want to change color of svg image(.svg). It is only possible using filter css property. I got the filter value from hex to css filter (library : hex-to-css-filter). it is giving correct value for color but react can not set filter property on that images. I tried using inline and also using root variable in css. Some code snippets describe below:

const filterValue = hexToCSSFilter('#575a98').filter;     // invert(40%) sepia(15%) saturate(1783%) hue-rotate(199deg) brightness(83%) contrast(84%)
document.documentElement.style.setProperty('--menu-image-filter', `${filterValue}`); 

Also in style.css

:root {
  --menu-image-filter: invert(79%) sepia(28%) saturate(1346%) hue-rotate(77deg) brightness(90%) contrast(85%); // Default
}


span.svg_path img{
    width: 35px;
    filter: var(--menu-image-filter);;
}

CodePudding user response:

You can convert the given svg url into text and then you can change the color by using the fill and stroke methods in CSS.

the code would be,

    function getTheSvg(url) {
        return fetch(url).then((res) => res.text());
    }
       const getTextFromSvg = async (url) => {

       let svgVal = await getTheSvg(url).then((res) => {

      return res;
    });
getTextFromSvg("https://yoururl.svg");
  • Related