- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −