Masking an image to the canvas

by mattdlockyer

HTML

<canvas id="c" width="400" height="400"></canvas>

CSS

body {
    background: #CEF;
}

JavaScript

var x = 0;
window.setInterval(function () {
    draw();
}, 25);
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
var imgReady = false;

function draw() {
    x -= 5;
    if (x < -img.width + 400) x = 0;
    if (imgReady) {
        // Save the state, so we can undo the clipping
        ctx.save();
        // Create a shape, of some sort
        ctx.beginPath();
        ctx.arc(200, 200, 200, 0, Math.PI * 2);
        // Clip to the current path
        ctx.clip();
        ctx.drawImage(img, x, 0);
        // Undo the clipping
        ctx.restore();
    }
}
// When the image is loaded, draw it
img.onload = function () {
    imgReady = true;
}
// Specify the src to load the image
img.src = "http://i.dailymail.co.uk/i/pix/2012/11/15/article-0-1609D0FF000005DC-373_964x641.jpg";