Convert svg xml text to png image using canvas

HTML5 canvas can used to draw image and also be converted to base64 image data url using toDataURL. Here is an example which will convert svg xml text to png (or any other format like jpeg) using this approach. Note that this works in Chrome/Firefox and does not work in IE.

<script src="//"></script>
<div>SVG: <span id="svg1"></span></div>
<div>Canvas:</div><canvas id="canvas1" width="200" height="70"></canvas>
<div>Png:<br/><img id="png1" src="" /></div>

<script type="text/javascript">
window.addEventListener("load", convert);
function convert() {
  var canvas = document.querySelector('#canvas1');
  var ctx = canvas.getContext('2d');
  var svgtext = '<svg xmlns="" width="100" height="50"><rect width="100" height="50" style="fill:green;" /><text x="20" y="20" style="font-size:14px;fill:white;">Hello</text></svg>';
  var svgImage = new Image();
  svgImage.onload = function() {
    ctx.drawImage(svgImage, 20, 10);
    $("#png1").attr("src", $("#canvas1").get(0).toDataURL());
  svgImage.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgtext);  
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments