Convert SVG to PNG and maintain CSS integrity

后端 未结 3 1048
眼角桃花
眼角桃花 2021-01-04 13:56

I am currently using canvg() and Canvas2Image to copy my SVG to a canvas and then convert the canvas to PNG. I would like to maintain the image format and not use PDF.

3条回答
  •  别那么骄傲
    2021-01-04 14:21

    Style definitions for svg elements defined in stylesheets are not applied to the generated canvas. This can be patched by adding style definitions to the svg elements before calling canvg.

    Inspired on this article, I've created this:

    function generateStyleDefs(svgDomElement) {
      var styleDefs = "";
      var sheets = document.styleSheets;
      for (var i = 0; i < sheets.length; i++) {
        var rules = sheets[i].cssRules;
        for (var j = 0; j < rules.length; j++) {
          var rule = rules[j];
          if (rule.style) {
            var selectorText = rule.selectorText;
            var elems = svgDomElement.querySelectorAll(selectorText);
    
            if (elems.length) {
              styleDefs += selectorText + " { " + rule.style.cssText + " }\n";
            }
          }
        }
      }
    
      var s = document.createElement('style');
      s.setAttribute('type', 'text/css');
      s.innerHTML = "";
      //somehow cdata section doesn't always work; you could use this instead:
      //s.innerHTML = styleDefs;
    
      var defs = document.createElement('defs');
      defs.appendChild(s);
      svgDomElement.insertBefore(defs, svgDomElement.firstChild);
    }
    
    // generate style definitions on the svg element(s)
    generateStyleDefs(document.getElementById('svgElementId'));
    

提交回复
热议问题