Compositing & Clipping
Compositing and clipping allow you to control how shapes overlap and create masks that limit the drawing area.
Compositing
By default, new shapes are drawn over existing shapes. You can change this behavior using the globalCompositeOperation property.
Commonly used values include:
| Value | Description |
|---|---|
source-over |
New shapes are drawn on top of the existing content (default). |
destination-over |
New shapes are drawn behind existing content. |
lighter |
New shapes blend with the existing content by adding the two color values together. |
xor |
Shapes are only drawn where they do not overlap. |
destination-out |
New shapes "erase" the existing content in overlapping areas. |
Compositing Example
This example draws shapes using destination-over which places the new shape behind ones that have already been drawn:
Clipping
The clip() method uses the current path to define a mask. Once the clipping region is set, all subsequent drawing is confined to that area.
Clipping Example
In this example, a circle is defined as the clipping path before drawing a large colorful rectangle:
The next lesson explains how to implement basic animations.