Canvas 2D Context

Part 8. Clipping and Masking

Clip your canvas according to your path
Rewritten proverb

Clipping Path

When a graphic object is rendered on the canvas plane, the affected region is limited by the current clipping path which is part of the graphics state. Primary clipping path embraces the entire canvas. The method clip() is used to modify the clipping region. The method is called after a path construction operation and before a painting command. In the example below clipping goes through the following stages:

  • the initial clipping path includes the entire canvas plane;
  • a new path (a triangle) acting as a stencil is being created;
  • clip() is invoked on the given CanvasRenderingContext2D instance and a new clipping region is built: this is an intersection of the primary clipping path and the triangle created before;
  • a filled rectangle is being painted; the newly created clipping path does not affect intrinsic geometry of the rectangle, but it determines its effective shape.

context.beginPath();
context.moveTo(10, 10);
context.lineTo(400, 10);
context.lineTo(200, 200);
context.closePath();

context.clip();

context.fillStyle="navy";
context.fillRect(10, 10, 410, 410);

Masking

Clipping can be considered an example of "hard" masking: a clipping path acts as a 1-bit mask, and any graphic object is drawn onto the canvas background through the mask. Pixels within the boundaries of the clipping path are displayed, pixels outside the path are masked out. Soft masking is not supported in HTML5 canvas implementations, but nothing keeps the developer from applying CSS masking properties to the canvas contents:

// CSS masking applied to the entire canvas
-webkit-mask-image: -webkit-linear-gradient (left, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 1.0) 100%);

// JavaScript
var image=new Image();
image.src="http://www.example.com/resources/city.png";
context.drawImage(image, 1, 1);

In the example above a linear gradient is used as a mask. The color of the gradient is constant, however, alpha value is changing from 0.5 to 1.0. The canvas is painted onto the background through the mask. As a result, the alpha channel of the canvas bitmap is multiplied with the mask's alpha values. The final effect is the existence of different levels of transparency in different points of the image drawn on the canvas: the image is semi-transparent on the left and completely opaque on the right.

Summary: Clipping

clipping path
context.clip();