HTML Canvas Convert to data URL

Introduction

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

var dataURL = canvas.toDataURL(); 

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.

View in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                // w ww.  j  a  v  a 2 s.  com
                var startX = 200;
                var 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();
                
                // save canvas image as data url (png format by default)
                var dataURL = canvas.toDataURL();
                
                // insert url into the HTML document so we can see it
                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>



PreviousNext

Related