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

 

 

Welcome folks today in this blog post we will be downloading png canvas image in browser using 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

 

 

<canvas id="canvas" width=240 height=240 style="background-color:#808080;">
</canvas>
<p></p>
<a id="download" download="myImage.jpg" href="" onclick="download_img(this);">Download to myImage.jpg</a>

 

 

 

Now make a script.js file and copy paste the following code for the logic of the application

See also  Javascript Tutorial to Convert Div Canvas to Downloadable PNG Image Using Filesaver.js and dom-to-image.js Library Full Project For Beginners

 

 

script.js

 

 

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#800";
ctx.fillRect(ox / 2, oy / 2, ox, oy);

download_img = function(el) {
  var image = canvas.toDataURL("image/jpg");
  el.href = image;
};

Leave a Reply