HTML5 Game - Saving the Canvas Drawing in an <img> Object via toDataURL() method

Introduction

The canvas's toDataURL() method returns a Base64-encoded representation of the drawing.

We can display the canvas drawing in an HTML image object.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*from w ww  .  j  a v  a 2 s .  co  m*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        context.fillRect(20, 20, 160, 160); 
        let data = canvas.toDataURL(); 
        $("#imgCanvas").attr("src", data); 

    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
  <img id='imgCanvas'/>
 </body>
</html>

Note

A rectangle is drawn on the canvas.

Then toDataURL() is called to retrieve the Base64-encoded representation of the canvas drawing.

Then we load this Base64 data into an <img> element by setting its src attribute.

The string begins with a MIME type for the image.

You can also specify the image type yourself using a variation of toDataURL():

let data = canvas.toDataURL("mage/png"); 

toDataURL() now takes the MIME type for the image.

Typical values include image/png and image/jpg.

The default image MIME type is image/png.

Related Topic