img src SVG changing the styles with CSS

后端 未结 22 2516
予麋鹿
予麋鹿 2020-11-22 01:16

html

\"Logo\"

css

.logo-img path {
           


        
22条回答
  •  半阙折子戏
    2020-11-22 01:46

    For me, my svgs looked different when having them as img and svg. So my solution converts the img to csv, changes styles internally and back to img (although it requires a bit more work), I believe "blob" also has better compatibility than the upvoted answer using "mask".

      let img = yourimgs[0];
      if (img.src.includes(".svg")) {
        var ajax = new XMLHttpRequest();
        ajax.open("GET", img.src, true);
        ajax.send();
        ajax.onload = function (e) {
         
          svg = e.target.responseText;
    
         
          svgText = "";
          //change your svg-string as youd like, for example
          // replacing the hex color between "{fill:" and ";"
          idx = svg.indexOf("{fill:");
          substr = svg.substr(idx + 6);
          str1 = svg.substr(0, idx + 6);
          str2 = substr.substr(substr.indexOf(";"));
          svgText = str1 + "#ff0000" + str2;
          
    
          let blob = new Blob([svgText], { type: "image/svg+xml" });
          let url = URL.createObjectURL(blob);
          let image = document.createElement("img");
          image.src = url;
          image.addEventListener("load", () => URL.revokeObjectURL(url), {
            once: true,
          });
          img.replaceWith(image);
        };
      }
    

提交回复
热议问题