Normally, when drawing additional shapes or paths onto a canvas, the new shape is placed over top of the old content that was previously on the canvas. However, there is a global property that alters this behavior: globalCompositeOperation. Setting this property to one of the various values will change the compositing method for all subsequent actions taken on the canvas. The compositing value is recorded and recalled with the context.save() and context.restore() functions.
All examples use the following base code, modifying only the value of globalCompositeOperation, as noted in each example.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height
ctx.fillStyle = 'red';
ctx.fillStyle = 'green';
ctx.globalCompositeOperation = "mode";
ctx.fillStyle = 'blue';
ctx.globalCompositeOperation = "source-over";
The "source-over" operation represents the default behavior. The new shapes and paths being drawn are placed on top of the previous content.
ctx.globalCompositeOperation = "destination-over";
The opposite of "source-over, the "destination-over" operation places the newly drawn shapes and paths behind the previous content.
ctx.globalCompositeOperation = "source-in";
The "source-in" operation draws the new shape only where it overlaps with the content below, and removes the intersected content.
note: webkit currently treats this like "source-atop"
ctx.globalCompositeOperation = "destination-in";
The "destination-in" operation keeps the intersected content only where it overlaps with the new shape. The new shape is not drawn.
note: webkit currently displays all of the old content
ctx.globalCompositeOperation = "source-out";
The opposite of "source-in", the "source-out" operation draws the new shape only where it does not intersect with the shape beneath it.
note: webkit currently treats this like "xor"
ctx.globalCompositeOperation = "destination-out";
The opposite of "destination-in", the "destination-out" operation keeps the intersected shape only where it not overlapped by the new shape.
ctx.globalCompositeOperation = "source-atop";
The "source-atop" operation draws the portion of the new shape only where it overlaps with the intersected shape beneath.
ctx.globalCompositeOperation = "destination-atop";
The "destination-atop" operation draws the new shape behind the old shape, and removes the portion of the old shape which does not overlap the new shape.
note: webkit currently treats this like "destination-over"
ctx.globalCompositeOperation = "xor";
The "xor" operation removes the intersecting portions of both the new shape and the underlying shape.