In this article I am going to explain SVG to PNG conversion using HTML5 Canvas.


As shown in the above picture there are 2 steps.
  1. Get SVG on HTML5 canvas
  2. Convert Canvas to PNG image

Get SVG on HTML5 canvas

// get Canvas Element
var myCanvas = document.getElementById('canvasid');
// get 2D context
var myCanvasContext = myCanvas.getContext('2d');
// Load up our image.
var source = new Image();
source.src = '/img/twitter.svg';
// Render our SVG image to the canvas once it loads.
source.onload = function(){
   myCanvasContext.drawImage(source,0,0,200,200);
}

Convert Canvas to PNG image

$("#resultImage").attr("src",myCanvas.toDataURL("image/png"));

7 comments:

  1. don't want to be critic, but I have a problem trying to use img.src = canvas.toDataURL(...) in Internet Explorer 11. A security issue rises. Your example here has the same problem. Have you found a workaround?. Thank you.

    ReplyDelete
    Replies
    1. use ( source.crossOrigin = "Anonymous"; )
      this will avoid security error

      Delete
  2. Its not render the external images refereed by SVG.

    ReplyDelete
    Replies
    1. use ( source.crossOrigin = "Anonymous"; )
      this will avoid security error

      Delete
  3. Is there a way where I can specify the ID of an SVG within the page as the source URL instead of an external SVG file?

    ReplyDelete
    Replies
    1. Use this

      var source = document.getElementById('give id here');

      Delete

Blogroll

Follow this blog by Email

Popular Posts