How to Export SVG Image in Browser to Base64 PNG Image Using Canvg Library in Browser Using Javascript Full Project For Beginners






    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
      <input id='downloadBtn' type='button' value='Download'/>
    <svg xmlns="" class="item" id="svg-01" width="600" height="250">
      <rect fill="none" stroke="#000" stroke-width="1" x="0" y="0" width="600" height="250" />
      <text class="item-title" style="font-family:monospace; font-size: 20px;" lengthAdjust="spacing" textLength="580" transform="translate(300,40)" text-anchor="middle">Export SVG as PNG using canvg.js and Canvas</text>



function SVG2PNG(svg, callback) {
  var canvas = document.createElement('canvas'); // Create a Canvas element.
  var ctx = canvas.getContext('2d'); // For Canvas returns 2D graphic.
  var data = svg.outerHTML; // Get SVG element as HTML code.
  canvg(canvas, data); // Render SVG on Canvas.
  callback(canvas); // Execute callback function.



function generateLink(fileName, data) {
  var link = document.createElement('a'); = fileName;
  link.href = data;
  return link;



document.getElementById('downloadBtn').onclick = function() { // Bind click event on download button.
  var element = document.getElementById('svg-01'); // Get SVG element.
  SVG2PNG(element, function(canvas) { // Arguments: SVG element, callback function.
    var base64 = canvas.toDataURL("image/png"); // toDataURL return DataURI as Base64 format.
    generateLink('SVG2PNG-01.png', base64).click(); // Trigger the Link is made by Link Generator and download.


See also  jQuery PrintThis Plugin Example to Print Specific Parts of HTML5 DOM in Webpage Using Javascript Full Project For Beginners


Leave a Reply