Advertisement
jargon

Js :: Download Canvas as PNG

Jul 4th, 2024
840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Canvas Download Example</title>
  5. </head>
  6. <body>
  7.     <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"></canvas>
  8.     <br>
  9.     <button id="downloadBtn">Download as PNG</button>
  10.  
  11.     <script>
  12.         // Get the canvas element and context
  13.         var canvas = document.getElementById('myCanvas');
  14.         var context = canvas.getContext('2d');
  15.  
  16.         // Draw something on the canvas
  17.         context.fillStyle = "blue";
  18.         context.fillRect(50, 50, 150, 100);
  19.  
  20.         // Function to download the canvas as a PNG
  21.         function downloadCanvas() {
  22.             // Create a link element
  23.             var link = document.createElement('a');
  24.             link.download = 'canvas.png';
  25.             link.href = canvas.toDataURL('image/png');
  26.             link.click();
  27.         }
  28.  
  29.         // Add event listener to the button
  30.         document.getElementById('downloadBtn').addEventListener('click', downloadCanvas);
  31.     </script>
  32. </body>
  33. </html>
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement