Canvas Clipping Example

Illustrating how to do clipping with canvas

by soulwire

HTML

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function randomCol() {
    var col = "rgba(R,G,B,A)";
    col = col.replace(/R/, Math.floor(Math.random() * 255));
    col = col.replace(/G/, Math.floor(Math.random() * 255));
    col = col.replace(/B/, Math.floor(Math.random() * 255));
    col = col.replace(/A/, 0.5 + Math.random() * 0.5);
    return col;
}

// Draw the mask for the shape
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(canvas.width, 0);
ctx.lineTo(canvas.width, canvas.height);
ctx.closePath();
ctx.clip();

// Now just do some stuff on the canvas
for (var i = 0; i < 200; ++i) {
    var px = Math.random() * canvas.width;
    var py = Math.random() * canvas.height;
    ctx.beginPath();
    ctx.fillStyle = randomCol();
    ctx.arc(px, py, Math.random() * 60, 0, Math.PI * 2);
    ctx.fill();
}

// Remember to restore
ctx.restore();