<body>
<canvas id="canvas"width=650 height=600></canvas>
<script>
var canvas = document.getElementById("canvas");
var c = canvas.getContext('2d');
var temp = document.createElement("canvas"); // Temporary canvas
temp.width = temp.height = 100;
var tc = temp.getContext('2d');
function destination() {
tc.fillStyle = "black";
tc.fillRect(5,5,70,70);
}
function source() {
tc.fillStyle = "yellow";
tc.beginPath()
tc.arc(50,50,40,0,Math.PI*2,true);
tc.fill();
}
temp.width = temp.width;
destination();
c.drawImage(temp, 200,25);
c.strokeRect(200,25,100,100);
c.fillText("Destination", 200, 20);
temp.width = temp.width;
source();
c.drawImage(temp, 350,25);
c.strokeRect(350,25,100,100);
c.fillText("Source", 350, 20);
var ops = [
"source-over", "destination-over",
"source-atop", "destination-atop",
"source-in", "destination-in",
"source-out", "destination-out",
"lighter", "xor", "copy"
];
for(var i = 0; i < ops.length; i++) {
var row = Math.floor(i/4), col = i%4;
var x = 50 + col*150;
var y = 150 + row*150;
temp.width = temp.width; //reset the temporary canvas
destination();
tc.globalCompositeOperation = ops[i];
source();
c.drawImage(temp, x,y)
c.strokeRect(x,y,100,100)
c.fillText(ops[i], x, y-5);
}
</script>
</body>