dsebao
9/26/2018 - 3:27 AM

SVG TO PNG

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
    text-align: center;
 }

#container {
    display: inline-block;
    padding: 2em;
    border: 0.062em solid #999;
    border-radius: 1em;
    background-color: #fff;
    box-shadow: inset 0 0 1em rgba( 0, 0, 0, 0.3 ), 
            0.4em 0.4em 0.4em rgba( 0, 0, 0, 0.3 );
 }

h1,h2 {
    font-size: 1em;
 }

svg, canvas {
    display:block;
    margin: 1em 0;
 }

.hide {
    display: none;
 }
</style>

</head>
<body> 

<div id="container">

 <h1>this is the svg image</h1>

  <svg width="170" height="112">

  
      <clippath id="circleView">
        <circle cx="50%" cy="50%" r="85" transform="translate(90 90)" fill="orange"></circle>
      </clippath>

    <image  x="50%" y="50%" transform="translate(-90 -90)" width="180" height="180" xlink:href="https://i.imgur.com/BO6KOvw.jpg" clip-path="url(#circleView)"></image>

  </svg>

 <button>svg to png</button>

 <h2 class="hide">this is the png image</h2>

 <canvas width="170" height="112"></canvas>

</div>

<script>
(function(w,d) {
   'use strict';

   var btn = d.querySelector( 'button' );
   var svg = d.querySelector( 'svg' );
   var canvas = d.querySelector( 'canvas' );

   var imageName ='your-image-name';

function triggerDownload ( imgURI ) {
   var evt = new MouseEvent( 'click', {
       view: w,
       bubbles: false,
       cancelable: true
    });

   var a = d.createElement( 'a' );
       a.setAttribute( 'download', imageName + '.png' );
       a.setAttribute( 'href', imgURI );
       a.setAttribute( 'target', 'blank' );
       a.dispatchEvent(evt);
    }

   btn.addEventListener( 'click', function () {

   var ctx = canvas.getContext( '2d' );
   var data = ( new XMLSerializer() ).serializeToString( svg );
   var DOMURL = w.URL || w.webkitURL || w;

   var img = new Image();
   var svgBlob = new Blob( [data], { type: 'image/svg+xml;charset=utf-8' } );
   var url = DOMURL.createObjectURL( svgBlob );

   img.onload = function () {
       ctx.drawImage( img, 0, 0 );
       DOMURL.revokeObjectURL( url );

    var imgURI = canvas
        .toDataURL( 'image/png' )
        .replace( 'image/png', 'image/octet-stream' );

    triggerDownload( imgURI );
  };
    img.src = url;
    d.querySelector( 'h2' ).classList.remove( 'hide' );
 });
}(window, document));
</script>