Skip to main content

Build

Masks and Stencils

PhaserOfficialCertified

Masking in Phaser 4: the Mask filter (enableFilters, then filters.internal or filters.external.addMask with a Game Object or texture key, invert, autoUpdate, hardEdges for Graphics and Shape masks), Stencil and StencilReference (addLayer, subtractLayer, clear, clearRegion, stencilInvert), CustomContext (scissor, stencil test, alpha strategy), the render config's alphaStrategy, stencil and stencilAlphaStrategy, and the Canvas-only GeometryMask. Use when masking a sprite, container or camera, cutting a hole in a dark overlay, a spotlight or keyhole, fog of war, a reveal or wipe, a circular minimap or avatar, or clipping a scrolling UI panel. v3's BitmapMask and createBitmapMask don't exist in v4, and setMask only works in Canvas. Triggers on: mask, masking, setMask, BitmapMask, GeometryMask, createGeometryMask, invertAlpha, inverted mask, hole, cut-out, clip, clipping, scissor, stencil, Stencil, StencilReference, CustomContext, alphaStrategy, dither.

  • New
  • v1.0.0
  • Reviewed Dec 4
  • No reviews yet

Capabilities

  • The Mask filter

  • Soft and hard edges

    Since 4.3, Graphics and Shapes draw circles, ellipses, rounded rectangles, lines and strokes as signed…

  • Masks drawn into a DynamicTexture

    A world-space mask doesn't follow the x and y offset given to dt.draw() or rt.draw()

  • Stencil

    A Stencil is a Container whose children are drawn into the stencil buffer, not to the screen

Getting started

Full instructions

Install the skill, then ask your AI tool for the task in plain words. The full SKILL.md below shows what it covers.

Instructions: SKILL.mdv1.0.0

Masks and stencils

In WebGL, Phaser 4 masks with the Mask filter or with a Stencil. The v3 BitmapMask is gone, and the GeometryMask only works in the Canvas Renderer. Everything here except the GeometryMask is WebGL only.

Source: src/filters/Mask.js, src/gameobjects/components/FilterList.js, src/gameobjects/stencil/Stencil.js, src/gameobjects/stencilreference/StencilReference.js, src/gameobjects/components/StencilModifier.js, src/gameobjects/customcontext/CustomContext.js, src/renderer/webgl/DrawingContext.js, src/display/mask/GeometryMask.js. Related: filters-and-postfx, graphics-and-shapes, render-textures, custom-rendering, phaser4-core.

Which one to use

You want Use
A mask on one object, Container, Layer or Camera, with soft edges, alpha or a gradient Mask filter
A hole in an overlay: spotlight, fog of war, tutorial highlight Mask filter with invert
A mask which follows an animated sprite Mask filter, internal
One sharp-edged cut-out over everything drawn after it, as cheap as possible Stencil
To end a Stencil's effect, part way down the display list StencilReference, or a Stencil in 'clear' mode
To clip a group to a rectangle on the screen, such as a scrolling list CustomContext with setScissorBox
To exempt some objects from a Stencil, or dither their alpha CustomContext
A mask in the Canvas Renderer GeometryMask with setMask
  • Mask filter: full alpha quality. It costs a framebuffer pass for each masked object, and the mask object is redrawn every frame. To mask many objects, put them in a Container or Layer and mask that.
  • Stencil: no framebuffer. It costs the draw calls of its children. Each pixel is in or out, with no partial alpha. It affects everything drawn after it, until the end of the frame.

Quick start: a hole in an overlay

js
create ()
{
    const { width, height } = this.scale;

    //  The Mask filter is WebGL only. In Canvas, see GeometryMask below.
    if (this.renderer.type !== Phaser.WEBGL)
    {
        return;
    }

    const overlay = this.add.graphics();
    overlay.fillStyle(0x000000, 0.8).fillRect(0, 0, width, height);

    //  make.graphics isn't added to the display list, so it is only drawn by the mask
    const hole = this.make.graphics();

    overlay.enableFilters();
    overlay.filters.internal.addMask(hole, true);  //  true: invert, so the overlay is hidden where the hole is

    this.input.on(Phaser.Input.Events.POINTER_MOVE, (pointer) =>
    {
        hole.clear().fillStyle(0xffffff).fillCircle(pointer.worldX, pointer.worldY, 100);
    });
}

The Mask filter

filters.internal.addMask(mask = '__WHITE', invert = false, viewCamera, viewTransform = 'world', scaleFactor = 1), or the same on filters.external, returns a Phaser.Filters.Mask. Call obj.enableFilters() first: obj.filters is null until then, and stays null in Canvas. Cameras always have filters.

  • mask is a Game Object or a texture key. Any Game Object works: a Graphics, Shape, Sprite, Text, Container, Layer or particle emitter. Only its alpha counts: opaque shows the masked object, transparent hides it, and the colour is ignored.
  • invert swaps them. Change it later with mask.invert = true.
  • A Game Object mask is drawn to an internal DynamicTexture every frame while mask.autoUpdate is true, the default. For a mask which doesn't change, set mask.autoUpdate = false. It is drawn once, and again after you set mask.needsUpdate = true.
  • The mask object needn't be on the display list: this.make.graphics() isn't added to it. If it is on the display list it is drawn there as well, so hide it with setVisible(false). The mask still works.
  • Filters on the mask object apply to the mask. A blurred mask object gives a feathered edge.
  • mask.setGameObject(obj), mask.setTexture(key) and mask.maskGameObject change or read the source.
  • viewTransform: 'world' places a mask object which is in a Container using the Container's transform. 'local' ignores the Container.
  • scaleFactor below 1 makes the mask texture smaller, to save memory. Scale the mask object by the same amount.
  • A Camera mask: this.cameras.main.filters.internal.addMask(maskObject).
  • Phaser.Actions.AddMaskShape(target, config) makes a circle, ellipse or rectangle mask, with an optional blur, in one call. See actions-and-utilities.

Where the mask object is placed

  • External masks (filters.external.addMask) are in world space, seen through the Camera, whatever the object.
  • Internal masks on Graphics, Shapes, Layers and Containers without a size are also in world space. These objects' filters render at the size of the Camera (see "Objects which focus on the context" in filters-and-postfx).
  • Internal masks on a sized object, such as a Sprite, Image, Text or TileSprite, cover the object's own frame:
    • A texture key is stretched over the object.
    • A mask Game Object is drawn in the object's local space. (0, 0) is the top-left of its unscaled frame, and the mask moves, scales and turns with the object. Use this for a mask which follows a sprite.
    • Call obj.setFiltersFocusContext(true) after enableFilters() to put the mask in world space instead.
    • Known issue in 4.3: the Camera's scroll and zoom also shift this kind of mask. When the Camera moves, use an external mask, or setFiltersFocusContext(true).
  • The mask object's own scroll factor applies. hole.setScrollFactor(0) keeps a world-space hole fixed on the screen.

Soft and hard edges

Since 4.3, Graphics and Shapes draw circles, ellipses, rounded rectangles, lines and strokes as signed distance fields. Their edge is smoothed across one pixel, so a mask made from them has a soft edge.

js
const hole = this.make.graphics({ hardEdges: true });  //  or graphics.setHardEdges(), shape.setHardEdges()

hardEdges makes every pixel fully in or out, and the shape stays round. It has no effect in Canvas or on shapes drawn with triangles. render: { sdfShapes: false } in the game config turns signed distance fields off everywhere.

Masks drawn into a DynamicTexture

A world-space mask doesn't follow the x and y offset given to dt.draw() or rt.draw(). Move the mask object by the same offset, render, then move it back:

js
const maskObject = this.make.graphics().fillStyle(0xffffff).fillCircle(512, 384, 100);
const target = this.add.rectangle(512, 384, 400, 100, 0x00ff00);

target.enableFilters();
target.filters.internal.addMask(maskObject);

//  Draw the target in the middle of an 800 x 200 texture
const dt = this.textures.addDynamicTexture('masked', 800, 200);
const offsetX = 400 - target.x;
const offsetY = 100 - target.y;

maskObject.x += offsetX;
maskObject.y += offsetY;
dt.draw(target, offsetX, offsetY).render();
maskObject.x -= offsetX;
maskObject.y -= offsetY;

See render-textures.

Stencil

A Stencil is a Container whose children are drawn into the stencil buffer, not to the screen. After it, WebGL only draws pixels where the stencil buffer is 0.

js
const { width, height } = this.scale;

//  Nothing drawn after this appears inside the circle
this.add.stencil(0, 0, [ this.add.circle(300, 300, 80, 0xffffff) ]);

//  Or, with stencilInvert, things drawn after it only appear inside the circle:
//  this.add.stencil(0, 0, [ this.add.circle(300, 300, 80, 0xffffff) ], { stencilInvert: true });

this.add.image(width / 2, height / 2, 'nebula');
  • this.add.stencil(x, y, children, options). The children are positioned relative to the Stencil, as in any Container, and are taken off the display list.
  • By default a Stencil hides what comes after it where its children draw. This is the opposite of a v3 GeometryMask. Set stencilInvert: true to show only inside the children. It costs one more draw.
  • It affects objects later in the display list, not earlier ones. Use depth or the order you add things in.
  • It lasts until the end of the frame. It also affects later Cameras and Scenes, such as a UI Scene drawn on top, unless you remove it.
  • Children with alpha: a stencil pixel is on or off. stencilAlphaStrategy decides what happens to partly transparent pixels:
    • 'dither' (the default, from render.stencilAlphaStrategy) keeps a dithered pattern;
    • a number from 0 to 1 keeps the pixels with an alpha above it;
    • 'keep' makes every drawn pixel solid, even transparent ones. This is rarely what you want.
  • Shader, Noise and PointLight children ignore the alpha strategy. Set stencilCompositeCheck: true to draw them through a framebuffer which handles it.
  • Since 4.3, Graphics and Shapes in a Stencil always have hard edges.
  • Overlapping children each add a layer, so the overlap counts twice. Avoid overlaps when you subtract or invert.
  • A Stencil inside a Stencil is drawn through a framebuffer, which costs more draws and loses antialiasing. Avoid nesting them.

Options

Pass these in options, or set them with setStencilLayerMode, setStencilInvert, setStencilAlphaStrategy, setStencilClearValue, setStencilValueWrap and setStencilCompositeCheck.

Option Default Notes
stencilLayerMode 'addLayer' 'addLayer' adds 1 where the children draw. 'subtractLayer' takes 1 away. 'clear' sets the whole buffer to stencilClearValue, without drawing the children. 'clearRegion' sets it where the children draw.
stencilInvert false Apply the layer everywhere the children don't draw. Only for addLayer and subtractLayer.
stencilAlphaStrategy 'dither' See above.
stencilClearValue 0 For clear and clearRegion. From 0 to 255.
stencilValueWrap true The buffer has 8 bits: 256 layers wrap to 0. false stops at 0 and 255, so subtracting below 0 does nothing.
stencilCompositeCheck 'auto' true or false skips the check for nested Stencils.

Ending a Stencil: StencilReference

A StencilReference draws a Stencil again, with its own options. Use it to take away a layer, so the objects after it are drawn normally:

js
const { width, height } = this.scale;
const reveal = this.add.stencil(0, 0, [ this.add.circle(300, 300, 120, 0xffffff) ], { stencilInvert: true });

this.add.image(width / 2, height / 2, 'secret');  //  only inside the circle

this.add.stencilreference(reveal, { stencilInvert: true, stencilLayerMode: 'subtractLayer' });

this.add.text(20, 20, 'Not masked');  //  drawn everywhere
  • this.add.stencilreference(targetStencil, options). It uses the target's children and transform, and its own options.
  • Its options start at the defaults, not the target's. Copy across what the target uses, such as stencilInvert, and change the mode.
  • It draws nothing once the target is destroyed.
  • this.add.stencil(0, 0, [], { stencilLayerMode: 'clear' }) resets the whole buffer instead, which ends every Stencil drawn before it.

CustomContext

A CustomContext is a Container which gives its children a changed DrawingContext. Its callback gets a copy of the current DrawingContext before the children are drawn, every frame.

js
const { width, height } = this.scale;

//  Clip a scrolling list to a rectangle on the screen
const list = this.add.text(120, 120, 'Line 1\nLine 2\nLine 3');
this.add.customcontext(0, 0, [ list ], (context) =>
{
    context.setScissorBox(100, 100, 400, 300);
});

//  Draw a sprite through any Stencil above it
const hero = this.add.sprite(width / 2, height / 2, 'hero');
this.add.customcontext(0, 0, [ hero ], (context) =>
{
    context.state.stencil.enabled = false;
});

//  Dither the alpha of a ghost, in place of blending it
const ghost = this.add.sprite(200, 200, 'ghost').setAlpha(0.5);
this.add.customcontext(0, 0, [ ghost ], (context) => context.setAlphaStrategy('dither'));
  • this.add.customcontext(x, y, children, callback). Set customContextCallback later to change it, or null for none.
  • Use the setters: setScissorBox(x, y, width, height), setScissorEnable(bool), setStencil(...), setAlphaStrategy(strategy), setColorWritemask(r, g, b, a), setBlendMode(mode).
  • The scissor box is in canvas pixels from the top-left, and doesn't scroll with the Camera. It replaces the Camera's own scissor, so children can draw outside the Camera's viewport.
  • Don't make a new framebuffer in the callback. Use a DynamicTexture.
  • In Canvas a CustomContext is a plain Container: the callback isn't called.

Render config

js
const config = {
    type: Phaser.AUTO,
    render: {
        alphaStrategy: 'keep',           //  the default
        stencil: true,                   //  the default
        stencilAlphaStrategy: 'dither'   //  the default
    }
};
  • alphaStrategy is the default for every object. 'dither', or a threshold from 0 to 1, discards pixels in place of blending them, which looks grainy. Keep 'keep', and use a CustomContext where you need it.
  • stencil: false makes no stencil buffers, which saves memory. Stencil and StencilReference then do nothing.
  • stencilAlphaStrategy is the default for new Stencils and StencilReferences.
  • Most Phaser shaders handle the alpha strategy. Custom shaders don't, unless they implement it. See custom-rendering.

Canvas: GeometryMask

The Canvas Renderer can't run filters or Stencils. It has the v3 GeometryMask, a clipping path:

js
if (this.renderer.type === Phaser.CANVAS)
{
    const { width, height } = this.scale;
    const shape = this.make.graphics().fillStyle(0xffffff).fillCircle(300, 300, 100);
    const sprite = this.add.sprite(width / 2, height / 2, 'hero');

    sprite.setMask(shape.createGeometryMask());
}
  • setMask(mask), clearMask(destroyMask), createGeometryMask(graphics), and camera.setMask(mask, fixedPosition).
  • Use a Graphics object for the geometry. A Shape isn't reliable: a filled Rectangle Shape draws itself and clips everything away.
  • It is in world space, hard-edged, and can be shared by many objects. It can't be inverted: v3's invertAlpha is gone.
  • In WebGL, setMask logs a warning and does nothing, and camera.setMask does nothing. A game set to Phaser.AUTO needs both paths: the Mask filter in WebGL, and a GeometryMask in Canvas.

From v3

v3 v4
new BitmapMask(scene, obj), obj.createBitmapMask(), setMask(bitmapMask) obj.enableFilters(); obj.filters.internal.addMask(maskObject)
setMask(geometryMask) in WebGL The Mask filter. GeometryMask is Canvas only.
mask.invertAlpha = true addMask(maskObject, true), or mask.invert = true
camera.setMask(mask) camera.filters.internal.addMask(maskObject)
Stencil-based geometry masks this.add.stencil(...)

Gotchas

  • enableFilters() comes first. obj.filters.internal.addMask(...) throws without it, and throws in Canvas.
  • A Stencil draws its children in Canvas. It is a plain Container there, so the cut-out shapes appear on screen. Only add Stencils in WebGL.
  • A Stencil leaks into later Scenes and Cameras in the same frame. End it with a StencilReference.
  • Stencil and Mask are opposites by default. An opaque Mask shows the object; a Stencil child hides what comes after it.
  • Masks don't change input. Hidden parts of an interactive object still get pointer events.
  • Mask edges are soft on Graphics and Shapes since 4.3. Use hardEdges for a crisp cut.
  • Many Mask filters are costly. Each is a framebuffer pass, plus a redraw of the mask object. Mask a Container or Layer, use autoUpdate = false for static masks, or use a Stencil.

Explore more skills

Browse all
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Signing

SignedSLSA L2
Signed by
skills-hub.ai distributor
Method
Distributor-signed by skills-hub.aiSigned with the skills-hub.ai Ed25519 distributor key over this exact slug, version and content. Check it with `npx @skills-hub-ai/cli verify`.
Key
skills-hub-ed25519-2026-11
Signed

Reviews (0)

More from Phaser

View source →
animationsShowcaseFrame animation in Phaser 4: the global Animation Manager (this.anims.create, generateFrameNumbers, generateFrameNames, createFromAseprite, addMix, staggerPlay) and each Sprite's Animation State (sprite.play, playReverse, chain, stop,…65 installsv4-new-featuresShowcaseA map of what Phaser 4.0 to 4.3 added, a few lines each, with the skill which covers it: Filters, render nodes, lighting and cone lights, tint modes and setTint2, CaptureFrame, Gradient, the Noise objects, Sky and its stars, World3D,…61 installssprites-and-imagesShowcaseCreate and use texture-based Game Objects in Phaser 4: Image and Sprite (this.add.image, this.add.sprite, setTexture, setFrame, setCrop, setDisplaySize, custom classes with scene.add.existing), NineSlice panels, TileSprite scrolling…55 installsgraphics-and-shapesShowcaseDraw vector shapes in Phaser 4 with the Graphics object (fillRect, fillCircle, fillRoundedRect, lineStyle, strokePath, arc, slice, generateTexture) and the Shape objects (this.add.rectangle, circle, arc, ellipse, line, polygon, star,…51 installsloading-assetsShowcaseLoad files with the Phaser 4 Loader (this.load): images, spritesheets, atlases (JSON, XML, multiatlas, Aseprite, compact atlasPCT), compressed textures, audio, video, JSON, tilemaps, fonts and packs. Covers preload vs this.load.start(),…46 installstilemapsShowcaseTile maps in Phaser 4: load.tilemapTiledJSON and load.tilemapCSV, make.tilemap, addTilesetImage, createLayer and createBlankLayer, TilemapGPULayer, getTileAt, putTileAt, removeTileAt, getTilesWithinShape, tile collision with…43 installs

Frequently asked questions about masks-and-stencils

What does the masks-and-stencils skill do?

Masking in Phaser 4: the Mask filter (enableFilters, then filters.internal or filters.external.addMask with a Game Object or texture key, invert, autoUpdate, hardEdges for Graphics and Shape masks), Stencil and StencilReference (addLayer, subtractLayer, clear, clearRegion, stencilInvert), CustomContext (scissor, stencil test, alpha strategy), the render config's alphaStrategy, stencil and stencilAlphaStrategy, and the Canvas-only GeometryMask. Use when masking a sprite, container or camera, cutting a hole in a dark overlay, a spotlight or keyhole, fog of war, a reveal or wipe, a circular minimap or avatar, or clipping a scrolling UI panel. v3's BitmapMask and createBitmapMask don't exist in v4, and setMask only works in Canvas. Triggers on: mask, masking, setMask, BitmapMask, GeometryMask, createGeometryMask, invertAlpha, inverted mask, hole, cut-out, clip, clipping, scissor, stencil, Stencil, StencilReference, CustomContext, alphaStrategy, dither. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the masks-and-stencils skill?

Run `npx @skills-hub-ai/cli install phaser-masks-and-stencils` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/phaser-masks-and-stencils/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does masks-and-stencils work with?

masks-and-stencils runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the masks-and-stencils skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use masks-and-stencils after installing it?

In Claude Code, type `/phaser-masks-and-stencils` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the masks-and-stencils skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.

Badge for your README

Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/phaser-masks-and-stencils)](https://skills-hub.ai/skills/phaser-masks-and-stencils)
HTML
<a href="https://skills-hub.ai/skills/phaser-masks-and-stencils"><img src="https://skills-hub.ai/api/badges/skill/phaser-masks-and-stencils" alt="Install on Skills Hub"></a>

More options in the badge docs.