Convert embedded SVG to PNG in-place

后端 未结 6 726
自闭症患者
自闭症患者 2020-11-29 17:20

I\'m generating HTML from a Docbook source while using SVG for images (converted from MathML). This works fine for some browsers that can interpret SVG, but fails for others

6条回答
  •  猫巷女王i
    2020-11-29 17:58

    I ran into this problem over the past weekend, and ended up writing a simple library to do more or less what Phrogz describes. It also hard codes the target SVG's style in order to avoid rendering issues. Hopefully the next person looking for a way to do this can simply use my code and move on to the more interesting challenges!

    P.S. I only tested this in Chrome.

    // Takes an SVG element as target
    function svg_to_png_data(target) {
      var ctx, mycanvas, svg_data, img, child;
    
      // Flatten CSS styles into the SVG
      for (i = 0; i < target.childNodes.length; i++) {
        child = target.childNodes[i];
        var cssStyle = window.getComputedStyle(child);
        if(cssStyle){
           child.style.cssText = cssStyle.cssText;
        }
      }
    
      // Construct an SVG image
      svg_data = '' + target.innerHTML + '';
      img = new Image();
      img.src = "data:image/svg+xml," + encodeURIComponent(svg_data);
    
      // Draw the SVG image to a canvas
      mycanvas = document.createElement('canvas');
      mycanvas.width = target.offsetWidth;
      mycanvas.height = target.offsetHeight;
      ctx = mycanvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
    
      // Return the canvas's data
      return mycanvas.toDataURL("image/png");
    }
    
    // Takes an SVG element as target
    function svg_to_png_replace(target) {
      var data, img;
      data = svg_to_png_data(target);
      img = new Image();
      img.src = data;
      target.parentNode.replaceChild(img, target);
    }
    

提交回复
热议问题