HTML5 Game - Canvas toDataURL

Converting a canvas drawing into a data URL

We can extract an image data URL.

It is a text string containing encoded information about the canvas image.

Data URLs are useful to save the canvas drawing in local storage or in an offline database.

The following code draws a shape, get its data URL, and then insert it into the HTML page.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <script>
         window.onload = function(){ 
             let canvas = document.getElementById("myCanvas"); 
             let context = canvas.getContext("2d"); 
              //  w  ww.  ja va 2  s  .  c  om
             let startX = 200; 
             let startY = 100; 
              
             // draw cloud shape 
             context.beginPath(); 
             context.moveTo(startX, startY); 
             context.bezierCurveTo(startX - 40, startY + 20, startX - 40, startY + 70, startX + 60, startY + 70); 

            context.closePath(); 
           
            context.lineWidth = 5; 
            context.fillStyle = "#8ED6FF"; 
            context.fill(); 
            context.strokeStyle = "#0000ff"; 
            context.stroke(); 
            let dataURL = canvas.toDataURL(); 

            document.getElementById("dataURL").innerHTML = "<b>dataURL:</b> " + dataURL; 
         }; 
        </script>
    </head>
    <body>
         <canvas id="myCanvas" width="600" height="250" style="border:1px  
         solid black;"> 
         </canvas> 
         <p id="dataURL" style="width:600px;word-wrap: break-word;"> 
         </p> 
    </body>
</html>

Note

The toDataURL() method converts a canvas drawing into a data URL:

let dataURL = canvas.toDataURL(); 

The URL starts with data:image/png;base64.

This means that the data URL is a PNG image which is represented by a base 64 encoding.

Related Topics