How to Download 2D Canvas Drawing as Static PNG Image in Browser Using Vanilla Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be downloading 2d canvas drawing as static png image in browser using vanilla javascript. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<h1>Download Canvas</h1>

<div id="container">
  <canvas id="canvas" width="200" height="200"></canvas>
  <button id="btndownload">Download</button>
</div>

 

 

 

Now make a style.css file and copy paste the following code

 

 

style.css

 

 

h1 {
  text-align: center;
}
#container {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  text-align: center;
}
#canvas {
  border: solid 1px gray;
  margin-bottom: 10px;
  display: block;
}

 

 

 

Now make a script.js file and copy paste the following code

 

 

script.js

 

 

// Initializing
window.onload = function(){
  var dwn = document.getElementById('btndownload'),
      canvas = document.getElementById('canvas'),
      context = canvas.getContext('2d');

  // Drawing a circle
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  var radius = 70;
  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.fillStyle = 'rgba(0,200,0, .7)';
  context.fill();
  context.lineWidth = 2;
  context.strokeStyle = 'black';
  context.stroke();
  
  // Drawing a rect
  context.beginPath();
  context.rect(15, 50, 100, 100);
  context.fillStyle = 'rgba(255,255,0, .7)';
  context.fill();
  context.lineWidth = 2;
  context.strokeStyle = 'black';
  context.stroke();

  // Event handler for download
  dwn.onclick = function(){
    download(canvas, 'myimage.png');
  }

}


// Source from:  http://stackoverflow.com/questions/18480474/how-to-save-an-image-from-canvas

/* Canvas Donwload */
function download(canvas, filename) {
  /// create an "off-screen" anchor tag
  var lnk = document.createElement('a'), e;

  /// the key here is to set the download attribute of the a tag
  lnk.download = filename;

  /// convert canvas content to data-uri for link. When download
  /// attribute is set the content pointed to by link will be
  /// pushed as "download" in HTML5 capable browsers
  lnk.href = canvas.toDataURL("image/png;base64");

  /// create a "fake" click-event to trigger the download
  if (document.createEvent) {
    e = document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window,
                     0, 0, 0, 0, 0, false, false, false,
                     false, 0, null);

    lnk.dispatchEvent(e);
  } else if (lnk.fireEvent) {
    lnk.fireEvent("onclick");
  }
}

Leave a Reply