Canvas Clipping

by mateuszwijas

HTML

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

CSS

body {
    background: #f1f1f1;
    width: 100%;
}

canvas {
    background: #fff;
    display: block;
    height: 150px;
    margin: 30px auto;
    width: 150px;
}

JavaScript

var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillRect(0, 0, 150, 150);

// create a clipping path
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 130);
ctx.lineTo(130, 130);
ctx.lineTo(130, 20);
ctx.clip();

// backgroud in clipped area
ctx.fillStyle = "#11c";
ctx.fillRect(0, 0, 150, 150);

// draw shapes inside clipped area
ctx.translate(75, 90);

ctx.fillStyle = '#f00';

ctx.fillRect(-15, -40, 40, 40);
ctx.fillRect(0, 0, 10, 10);
ctx.fillRect(-25, 10, 60, 60);