How Pixi.js Masks Work to Hide Display Objects

In Pixi.js, masking is a powerful technique used to restrict the visibility of a display object to a specific shape or area. This article explains the underlying mechanics of how masks work in Pixi.js, distinguishes between the two primary types of masks—graphics and sprite masks—and outlines how to implement them efficiently in your WebGL applications.

The Core Concept of Masking

At its core, a mask in Pixi.js is a display object applied to another display object (or container) via the .mask property. When a mask is applied, Pixi.js modifies the rendering pipeline so that only the portions of the target object that overlap with the geometry or alpha channel of the mask are drawn to the screen.

To apply a mask, you assign the mask object directly to the target’s mask property:

targetDisplayObject.mask = maskObject;

To remove the mask and restore full visibility, you simply set the property back to null:

targetDisplayObject.mask = null;

Types of Masks in Pixi.js

Pixi.js supports two main types of masks, each utilizing a different rendering technique depending on the type of display object used as the mask.

1. Graphics Masks (Geometry-Based)

Graphics masks use a PIXI.Graphics object to define the visible area.

2. Sprite Masks (Alpha-Based)

Sprite masks use a PIXI.Sprite (an image or texture) to define the visible area.


Key Rules and Best Practices

To ensure masks render correctly and perform well in your project, keep the following rules in mind: