Dec 252010
 

The canvas element in HTML5 is akin to a drawingboard on a webpage. It allows dynamic drawing of images, animation through JavaScript. The programming model is relatively simple and easy to learn. I just started playing around with it and tried to draw a heart shape with it.

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        function onload() {
            var drawingCanvas = document.getElementById('drawing');

            // Check the element is in the DOM and the browser supports canvas
            if (drawingCanvas.getContext) {
                var context = drawingCanvas.getContext('2d');
                context.beginPath();
                context.lineCap = "round";
                context.lineWidth = 8;
                context.strokeStyle = "red";
                context.fillStyle = "red";
                context.moveTo(100, 90);
                context.quadraticCurveTo(105,150,200, 215); 
                context.quadraticCurveTo(290, 150,300, 90);
                context.quadraticCurveTo(250, 30, 200, 90);
                context.quadraticCurveTo(150, 30, 100, 90);
                context.stroke();
                context.fill();

            }
        }
    </script>
</head>
<body onload="onload()">
<canvas style="margin:10px" id="drawing" width="500" height="500">
</canvas>
</body>
</html>

The whole shape is called a path. You can draw lines, arcs, curves etc to make up a path and then fill it with a color. Canvas also allows for more advanced stuff like animation etc, but that is fodder for later posts. Below is the demo. The page is available here. (Might not work in a bit older browsers. Use Chrome).