Wednesday, December 19, 2012

HTML5 Canvas

Here is a cool little demo of the canvas element in HTML5.  This page will create an interactive gradient fill based on your mouse position within the canvas element.  It changes the color pattern based on the mouse moving and the control or shift key being held while moving.  It is a simple little demo illustrating the flexibility of this new element.  In Visual Studio 2012, create a new html page with the attached code sample.  It's a good learning exercise on uses for the canvas element.  You can take the same basic premise and make scribble pad out of the control. 

<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Messing</title>
<style>
body 
{
  background: #fff;
}
canvas 
{
 
  height: 480px;
  width: 600px;
}
</style>
</head>
<body>
<canvas height="480" width="600"/>
<script>
    var canvas = document.getElementsByTagName('canvas')[0],
        ctx = null,
        grad = null,
        body = document.getElementsByTagName('body')[0],
        color = 255;

    if (canvas.getContext('2d'))
    {
        ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, 600, 480);
        ctx.save();
        // Create radial gradient
        grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 480);
        grad.addColorStop(0, '#fff');
        grad.addColorStop(1, 'rgb(' + color + ', ' + color + ', ' + color + ')');

        // Assign gradients to fill
        ctx.fillStyle = grad;

        // Draw 600x480 fill
        ctx.fillRect(0, 0, 600, 480);
        ctx.save();

        body.onmousemove = function (event)
        {
            var width = 600,
                height = 480,
                x = event.clientX,
                y = event.clientY,
                rx = 480 * x / width,
                ry = 600 * y / height;

            var xc = Math.floor(256 * x / width);
            var yc = Math.floor(256 * y / height);
            if (event.shiftKey || event.ctrlKey)
            {
                grad = ctx.createRadialGradient(rx, ry, 0, rx, ry, 600);
                grad.addColorStop(0, '#000');
                grad.addColorStop(1, ['rgb(', xc, ', ', (255 - xc), ', ', yc, ')'].join(''));                
                ctx.fillStyle = grad;
                ctx.fillRect(0, 0, 600, 480);
                
            }
        };
    }
</script>
</body>
</html>