HTML Canvas convert to image

Description

HTML Canvas convert to image

View in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                //from   w  w  w. j a va2  s .c  om
                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();
                
                // set canvasImg image src to dataURL
                // so it can be saved as an image
                document.getElementById("canvasImg").src = dataURL;
            };
        </script>
    </head>
    <body>
        <p>
            Canvas:
        </p>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
        <p>
            Image:
        </p>
        <img id="canvasImg" alt="Right click to save me!" 
             style="display: block; border:1px solid black;">
    </body>
</html>



PreviousNext

Related