Masking an image to the canvas

by julienbidoret

HTML

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

CSS

body {
    background: #fff;
}

JavaScript

// 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');

// When the image is loaded, draw it
img.onload = function () {

    // Save the state, so we can undo the clipping
    ctx.save();
    
    
    // Create a shape, of some sort
    ctx.beginPath();
    ctx.moveTo(20, 0);
    ctx.lineTo(240, 0);
    ctx.lineTo(220, 240);
    ctx.lineTo(0, 240);
    ctx.closePath();
    // Clip to the current path
    ctx.clip();
    
    
    ctx.drawImage(img, 0, 0);
    
    // Undo the clipping
    ctx.restore();
}

// Specify the src to load the image
img.src = "http://upload.wikimedia.org/wikipedia/commons/2/2b/Clouds.JPG";