HTML5 Game - Exporting the canvas as an image

Description

Exporting the canvas as an image

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Pushing canvas further</title>
    <meta charset="utf-8">
    /*from   w ww  .  j  a  v  a 2 s  .  co m*/
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        context.save();
        context.fillRect(50, 50, 100, 100);
        
        context.fillStyle = "rgb(255, 0, 0)";
        context.fillRect(100, 100, 100, 100);
        
        context.restore();
        context.fillRect(150, 150, 100, 100);
        
        // Convert the canvas into an image data URL
        let dataURL = canvas.get(0).toDataURL();
        let img = $("<img></img>");
        img.attr("src", dataURL);
        
        // Replace the canvas with the image of the canvas
        canvas.replaceWith(img);
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above draws a selection of squares, and assign the image data URL to the dataURL variable.

The encoded string is for png format.

The default encoding format is png.

The canvas specification supports other types of images using the toDataURL method.

PNG support is the default requirement.

Related Topic