Advanced Compositing

By default, images are layered on the canvas in drawing order, with new images layered on top of older images. Also by default, images that have areas with alpha values less than 1 are partly or wholly transparent, letting lower layers show through to varying degrees.

The web page background is the lowest layer, followed by any HTML elements positioned beneath the canvas element. Any CSS background applied to the canvas element comes next, followed by anything drawn on the canvas, with the most recent image, line, or shape in the top layer.

The canvas element also supports a global alpha channel. The global alpha channel can be set to any value between 0 and 1, inclusive, and defaults to 1. All drawing operations have their alpha values multiplied by the global alpha value, and so can be attenuated to any degree, up to full transparency. This allows you to draw semitransparent images, even if the source image has no alpha channel.

The global alpha value, simple layering, and the default alpha-channel compositing mode provide sufficient compositing capabilities for most applications, but canvas has ten other built-in compositing modes in addition to the default mode, and supports vendor-specific extensions as well.

Global Alpha

The global alpha value allows you to draw with varying degrees of transparency. Set the global alpha value by assigning it to the context’s globalAlpha property.

ctx.globalAlpha = alpha

The alpha value must be a number between 0 and 1, inclusive.

A value of 1 does not change the native alpha value of images, colors, gradients, or patterns. No transparency is added.

A value of less than 1 reduces the alpha values of all drawing operations proportionately.

A value of 0 causes all subsequent drawing operations to render transparently.

Compositing Modes

The canvas element has eleven built-in compositing modes, including the default mode, and support for vendor-specific extensions. You set a compositing mode by setting the context’s globalCompositeOperation property to one of these values:

Example: ctx.globalCompositeOperation = "copy";

Compositing deals with a source (the image being drawn), and a destination (the canvas and anything already on it).

Source and destination pixels can be opaque (alpha = 1), transparent (alpha = 0), or translucent (0 < alpha < 1).

The result of the composition can be to display the source pixel, the destination pixel, a transparent pixel (erase both source and destination to transparent), or a combination pixel, which uses values from the source and destination, combined using an algorithm.

A detailed description of the composition modes follows.