HTML5 Game - Saving a canvas drawing as an image

Introduction

We can use an image data URL to save the canvas drawing as an image.

The following code gets the image data URL of the canvas drawing and set it to the source of an image object.

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 w w  .java 2s.  c o m*/
             // draw cloud 
             context.beginPath(); // begin custom shape 
             context.moveTo(170, 80); 
             context.bezierCurveTo(130, 100, 130, 150, 230, 150); 
             context.closePath(); // complete custom shape 
            context.lineWidth = 5; 
            context.fillStyle = "#8ED6FF"; 
            context.fill(); 
            context.strokeStyle = "#0000ff"; 
            context.stroke(); 

            // save canvas image as data url (png format by default) 
            let dataURL = canvas.toDataURL(); 

            // set canvasImg image src to dataURL 
            // so it can be saved as an image 
            document.getElementById("canvasImg").src = dataURL; 
         }; 
</script>
<body>
         <canvas id="myCanvas" width="578" height="200"> 
         </canvas> 
         <p> 
            Image: 
         </p> 
         <img id="canvasImg" alt="Right click to save me!"> 
    </body>
</html>

Note

After drawing something on the canvas, we can create an image that the user can save by getting the image data URL using the toDataURL() method.

Then we set the source of an image object to the data URL.

Related Topic