Convert embedded SVG to PNG in-place

后端 未结 6 665
自闭症患者
自闭症患者 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条回答
  •  醉梦人生
    2020-11-29 18:19

    Demo: http://phrogz.net/SVG/svg_to_png.xhtml

    1. Create an img and set its src to your SVG.
    2. Create an HTML5 canvas and use drawImage() to draw that image to your canvas.
    3. Use toDataURL() on the canvas to get a base64 encoded PNG.
    4. Create an img and set it's src to that data URL.
    var mySVG    = document.querySelector('…'),      // Inline SVG element
        tgtImage = document.querySelector('…'),      // Where to draw the result
        can      = document.createElement('canvas'), // Not shown on page
        ctx      = can.getContext('2d'),
        loader   = new Image;                        // Not shown on page
    
    loader.width  = can.width  = tgtImage.width;
    loader.height = can.height = tgtImage.height;
    loader.onload = function(){
      ctx.drawImage( loader, 0, 0, loader.width, loader.height );
      tgtImage.src = can.toDataURL();
    };
    var svgAsXML = (new XMLSerializer).serializeToString( mySVG );
    loader.src = 'data:image/svg+xml,' + encodeURIComponent( svgAsXML );
    

    However, this answer (and all client-side only solutions) require the browser to support SVG, which may make it useless for your specific needs.

    Edit: This answer assumes that the SVG is available as a separate URL. Due to the problems described in this question I cannot get the above to work with an SVG document embedded in the same document performing the work.

    Edit 2: The problems described in that other question have been overcome by improvements to Chrome and Firefox. There is still the limitation that the element must have width="…" height="…" attributes for Firefox to allow it to be drawn to a canvas. And Safari currently taints the entire canvas whenever you draw any SVG to it (regardless of source) but that should change soon.

提交回复
热议问题