How to convert HTML canvas to png image using javascript

HTML canvas element (HTML5) be used to draw 2D shapes using Javascript. Once a shape is drawn, it can also be converted to an image (png, jpeg, etc.) and can be embedded in the HTML page using <img> tag and hence can also be downloaded. Here are the steps to achieve this:

  1. First create an empty canvas element as shown below:
    <canvas id="canvasid" width="200" height="100"></canvas>
  2. Then draw some basic shape in it. Here is the javascript code to draw a simple square:
    var canvas = document.getElementById('canvasid');
    var context = canvas.getContext('2d');
  3. Now using canvas toDataURL("image/png") get the png image url and populate the src attribute of required image. You may also want to see Canvas element reference. Here is how the code looks like:
    <img id="canvasimg" src="" />
    <script type="text/javascript">
    $("#canvasimg").attr("src", $("#canvasid").get(0).toDataURL("img/png"));
     Note that the value returned by toDataURL("image/png") looks something like this:

  4. Here is how the final image looks like:
    canvas-to-png-image-exampleYou can see the live demo at Canvas to image example.
  5. To download the image, you can right click on it and download as a regular image.

Notes on browsers compatibility

Canvas being HTML5 element is not supported by old browsers like IE8. It should work in browsers like Chrome, Firefox, IE9, etc. which support HTML5.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments