How to capture HTML Canvas as gif/jpg/png/pdf with JavaScript?


We can Use the canvas.toDataURL() to capture HTML canvas as different file formats, such as gif, png, jpg, webp, etc.

Capture HTML Canvas as png

Example

Herein, after using canvas.DataURL(), set the type to image/png to allow saving the image as PNG −

<!DOCTYPE html>
<html>
<body>
   <canvas id="myCanvas" width="300" height="170" style="border:2px solid #d3d3d3;"></canvas>
   <script>
      window.onload = function() {
         var canvas = document.getElementById("myCanvas");
         var context = canvas.getContext("2d");
         context.fillStyle = "red";
         context.fillRect(50, 50, 100, 100);
         window.location = canvas.toDataURL("image/png");
      }
   </script>
</body>
</html>

Output

Right-click in the canvas and you will get an option to save it -

Click Save image as… and now you can save the image. Let us save it on the Desktop as mycanva.png. Under Save as type:, PNG Image is visible because in the code, we wrote image/png

Capture HTML Canvas as webp

Example

Herein, after using canvas.DataURL(), set the type to image/webp to allow saving the image as WebP. WebP is an image file format developed by Google projected as a replacement for JPEG, PNG, and GIF file formats −

<!DOCTYPE html>
<html>
<body>
   <canvas id="myCanvas" width="300" height="170" style="border:2px solid #d3d3d3;"></canvas>
   <script>
      window.onload = function() {
         var canvas = document.getElementById("myCanvas");
         var context = canvas.getContext("2d");
         context.fillStyle = "red";
         context.fillRect(50, 50, 100, 100);
         window.location = canvas.toDataURL("image/webp");
      }
   </script>
</body>
</html>

Output

Right-click in the canvas and you will get an option to save it −

Click Save image as… and now you can save the image. Let us save it on the Desktop as mycanva.web Under Save as type:, webP Image is visible because in the code, we wrote image/webp


Updated on: 06-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements