Skip to main content
Version: Phaser v4.2.1

Stencil

A Stencil Game Object.

A Stencil is a special type of Game Object used to place stencils over the canvas. You can use it to efficiently control where subsequent objects are rendered. It is WebGL-only. Study the documentation carefully to understand how it works.

A Stencil is an extended Container Game Object. It contains a list of child Game Objects to render to the stencil buffer. Think of these as opaque sheets of card held up over the canvas, preventing anything from being drawn through them.

The stencil buffer is provided by WebGL. It is available if the game render config set stencil to true. It is an 8-bit attachment to framebuffers, like an extra alpha channel. But if the stencil channel is not 0 at a pixel, WebGL will skip rendering that pixel. There are no degrees of transparency, only on or off.

When you draw objects with alpha to a Stencil, a special alphaStrategy is used. Compatible shaders switch from rendering alpha, to discarding fragments based on their alpha value. By default, this uses dithering to preserve alpha gradients. You can change stencilAlphaStrategy to a threshold value to instead discard without dithering. If stencilAlphaStrategy is 'keep', or the child's shader does not support alpha strategies, transparent pixels will be drawn as opaque to the stencil buffer! This is rarely what you want. Fragment shaders must discard fragments for them to be transparent to the stencil buffer.

By default, most Phaser shaders support alpha strategies. Notable exceptions include:

  • PointLight (additive lighting)

  • Shader game objects, and extended classes like Noise

To apply an alpha strategy without a compatible shader, force stencil composition by setting stencilCompositeCheck to true. This will composite the stencil contents to a framebuffer, which is rendered using a compatible shader.

Stencils are drawn as order-independent layers. You can add or remove layers in sequence using addLayer and removeLayer. Each layer adds or subtracts 1 from the stencil buffer. Only when the stencil is 0 at a pixel will anything be drawn there. (This 0-test is a rule set by the renderer's base DrawingContext.) Note that overlapping geometry within the same Stencil is additive, and can adjust the layer by more than 1 in aggregate. The results can be surprising, so try to avoid overlaps.

You can invert the stencil by setting stencilInvert to true. This will use an extra draw call to invert the stencil: it adds a layer everywhere that the children would not draw. It is more efficient to render a shape that covers the whole area you wish to stencil, but if that's not possible, you can use this. Inversion makes it possible to render to parts of the screen not touched by child geometry. It works by filling the camera, then drawing the child stencil in reverse.

You can remove the stencil by using Phaser.GameObjects.StencilReference. This object copies a target Stencil, and re-renders it with different stencil options, elsewhere in the display list. This is an efficient way to re-use stencil geometry.

You can also clear the stencil by setting stencilLayerMode to clear. It replaces all stencil buffer values with the stencilClearValue. This should normally set them back to 0 so everything renders again. This destroys all layer information. It does not use the child list. Be careful not to mess up your scene this way.

Set stencilLayerMode to clearRegion to fill a region of the stencil buffer defined by the children, with the stencilClearValue. This can be used as a selective eraser, or to set a region to a specific value.

You cannot invert the stencil if the stencilLayerMode is clear or clearRegion.

Sequential stencil layers combine and persist, because they are drawn to the stencil buffer and stay there until the next frame. Do not add too many layers, though. There are only 8 bits in the stencil buffer, so it only safely supports 255 layers. If you go over this limit, the buffer wraps back to 0. You can still add and remove layers in this case, and they will continue to be accurately tracked, but layer 256 (and subsequent multiples of 256) will be effectively 0 and allow drawing. The same applies if you remove layers below 0: it wraps back to 255 and prevents drawing.

Deactivate stencilValueWrap to prevent the stencil buffer from wrapping. This is useful when defining stencils with subtraction, and you don't want to underflow from 0 to 255. For example, you can use one stencil in clearRegion to define a value, then use another stencil in subtractLayer to erase parts of that region. But be careful when using stencils for different purposes: if you mix stencil data, you will get unexpected results.

Nested stencils are a separate concern. If you add a Stencil as the child of another Stencil, the parent Stencil will composite its contents to a framebuffer, including child stencils. This effectively traps the child stencil in the framebuffer, and only the final composite from the framebuffer needs to be considered. It is used as the source for the stencil, subject to alpha strategy. This requires extra draw calls to composite, and framebuffers have poor anti-aliasing quality, so you should avoid nesting stencils unless you know what you are doing.

To determine whether the stencil needs to composite to a framebuffer, it runs a check before rendering ('auto' mode). If you know the answer already, or if you have a custom game object that Phaser doesn't understand, you can set stencilCompositeCheck to true or false to skip the auto check. If you set it to false, it will never composite, and any child stencils may render in unexpected ways. (Generally, they will appear backwards from what you expect: child stencils will not affect the parent stencil, but things drawn later.)

Best practice: use few stencils and don't nest them.

Stencil is best used for efficient, sharp-edged, reused masks. You can draw a stencil once, and it will affect everything that is drawn later. Its rendering cost is minimal: it is just the draw cost of its children. This can be as low as 1 call. If there are nested stencils, it will take more calls for the framebuffer.

If you need better quality alpha handling, consider using a Mask filter instead. Filters have a higher rendering cost, and apply to just 1 object at a time, but they have the best quality. (And you can apply them to Containers, to cheat the object limitation.)

Constructor

new Stencil(scene, x, y, [children], [options])

Parameters

nametypeoptionaldescription
scenePhaser.SceneNoThe Scene to which this Game Object belongs.
xnumberNoThe horizontal position of this Game Object in the world.
ynumberNoThe vertical position of this Game Object in the world.
childrenArray.<Phaser.GameObjects.GameObject>YesAn optional array of Game Objects to add to the Stencil.
optionsPhaser.Types.GameObjects.Stencil.StencilOptionsYesThe options for the Stencil.

Scope: static

Extends

Phaser.GameObjects.Container
Phaser.GameObjects.Components.StencilModifier

Source: src/gameobjects/stencil/Stencil.js#L12
Since: 4.2.0

Inherited Methods​

From Phaser.Events.EventEmitter:

From Phaser.GameObjects.Components.AlphaSingle:

From Phaser.GameObjects.Components.BlendMode:

From Phaser.GameObjects.Components.ComputedSize:

From Phaser.GameObjects.Components.Depth:

From Phaser.GameObjects.Components.Filters:

From Phaser.GameObjects.Components.Mask:

From Phaser.GameObjects.Components.RenderSteps:

From Phaser.GameObjects.Components.StencilModifier:

From Phaser.GameObjects.Components.Transform:

From Phaser.GameObjects.Components.Visible:

From Phaser.GameObjects.Container:

From Phaser.GameObjects.GameObject:


Public Methods​

hasStencilChildren​

<instance> hasStencilChildren(gameObject, camera)​

Description:

Checks if the game object or any of its children has a stencil. This is used internally to determine if the stencil should composite its contents to a framebuffer.

This is a depth-first, succeed-fast search.

Parameters:

nametypeoptionaldescription
gameObjectPhaser.GameObjects.GameObjectNoThe Game Object to check.
cameraPhaser.Cameras.Scene2D.CameraNoThe camera to check.

Returns: boolean - Whether the game object or any of its children has a stencil.

Source: src/gameobjects/stencil/Stencil.js#L408
Since: 4.2.0


stencilRenderStep​

<instance> stencilRenderStep(renderer, gameObject, drawingContext, [parentMatrix], [renderStep], [displayList], [displayListIndex])​

Description:

The stencil render step. This is an internal function, which is automatically assigned; you should not call it directly.

This runs before other render steps, so it can set up the drawing context to render properly. It delegates to the appropriate render step function based on the stencilLayerMode.

Tags:

  • webglOnly

Parameters:

nametypeoptionaldefaultdescription
rendererPhaser.Renderer.WebGL.WebGLRendererNoA reference to the current active WebGL renderer.
gameObjectPhaser.GameObjects.GameObjectNoThe Game Object being rendered in this call.
drawingContextPhaser.Renderer.WebGL.DrawingContextNoThe current drawing context.
parentMatrixPhaser.GameObjects.Components.TransformMatrixYesThis transform matrix is defined if the game object is nested
renderStepnumberYes0The index of this function in the Game Object's list of render processes. Used to support multiple rendering functions.
displayListArray.<Phaser.GameObjects.GameObject>YesThe display list which is currently being rendered.
displayListIndexnumberYesThe index of the Game Object within the display list.

Source: src/gameobjects/stencil/Stencil.js#L208
Since: 4.2.0


stencilRenderStepClear​

<instance> stencilRenderStepClear(renderer, gameObject, drawingContext, [parentMatrix], [renderStep], [displayList], [displayListIndex])​

Description:

The render step used when the stencilLayerMode is clear. You should not call this directly.

Tags:

  • webglOnly

Parameters:

nametypeoptionaldefaultdescription
rendererPhaser.Renderer.WebGL.WebGLRendererNoA reference to the current active WebGL renderer.
gameObjectPhaser.GameObjects.GameObjectNoThe Game Object being rendered in this call.
drawingContextPhaser.Renderer.WebGL.DrawingContextNoThe current drawing context.
parentMatrixPhaser.GameObjects.Components.TransformMatrixYesThis transform matrix is defined if the game object is nested
renderStepnumberYes0The index of this function in the Game Object's list of render processes. Used to support multiple rendering functions.
displayListArray.<Phaser.GameObjects.GameObject>YesThe display list which is currently being rendered.
displayListIndexnumberYesThe index of the Game Object within the display list.

Source: src/gameobjects/stencil/Stencil.js#L326
Since: 4.2.0


stencilRenderStepClearRegion​

<instance> stencilRenderStepClearRegion(renderer, gameObject, drawingContext, [parentMatrix], [renderStep], [displayList], [displayListIndex])​

Description:

The render step used when the stencilLayerMode is clearRegion. You should not call this directly.

Tags:

  • webglOnly

Parameters:

nametypeoptionaldefaultdescription
rendererPhaser.Renderer.WebGL.WebGLRendererNoA reference to the current active WebGL renderer.
gameObjectPhaser.GameObjects.GameObjectNoThe Game Object being rendered in this call.
drawingContextPhaser.Renderer.WebGL.DrawingContextNoThe current drawing context.
parentMatrixPhaser.GameObjects.Components.TransformMatrixYesThis transform matrix is defined if the game object is nested
renderStepnumberYes0The index of this function in the Game Object's list of render processes. Used to support multiple rendering functions.
displayListArray.<Phaser.GameObjects.GameObject>YesThe display list which is currently being rendered.
displayListIndexnumberYesThe index of the Game Object within the display list.

Source: src/gameobjects/stencil/Stencil.js#L352
Since: 4.2.0


stencilRenderStepLayers​

<instance> stencilRenderStepLayers(renderer, gameObject, drawingContext, [parentMatrix], [renderStep], [displayList], [displayListIndex])​

Description:

The render step used when the stencilLayerMode is addLayer or subtractLayer. You should not call this directly.

Tags:

  • webglOnly

Parameters:

nametypeoptionaldefaultdescription
rendererPhaser.Renderer.WebGL.WebGLRendererNoA reference to the current active WebGL renderer.
gameObjectPhaser.GameObjects.GameObjectNoThe Game Object being rendered in this call.
drawingContextPhaser.Renderer.WebGL.DrawingContextNoThe current drawing context.
parentMatrixPhaser.GameObjects.Components.TransformMatrixYesThis transform matrix is defined if the game object is nested
renderStepnumberYes0The index of this function in the Game Object's list of render processes. Used to support multiple rendering functions.
displayListArray.<Phaser.GameObjects.GameObject>YesThe display list which is currently being rendered.
displayListIndexnumberYesThe index of the Game Object within the display list.

Source: src/gameobjects/stencil/Stencil.js#L252
Since: 4.2.0


Inherited Members​

From Phaser.GameObjects.Components.AlphaSingle:

From Phaser.GameObjects.Components.BlendMode:

From Phaser.GameObjects.Components.ComputedSize:

From Phaser.GameObjects.Components.Depth:

From Phaser.GameObjects.Components.Filters:

From Phaser.GameObjects.Components.Mask:

From Phaser.GameObjects.Components.StencilModifier:

From Phaser.GameObjects.Components.Transform:

From Phaser.GameObjects.Components.Visible:

From Phaser.GameObjects.Container:

From Phaser.GameObjects.GameObject: