Write your own WebGL rendering in Phaser 4: the Shader Game Object (this.add.shader, ShaderQuadConfig, #pragma phaserTemplate, setupUniforms, shader additions, setRenderToTexture), custom filters (a Phaser.Filters.Controller plus a BaseFilterShader render node, addNodeConstructor, padding), custom render nodes (render.renderNodes, setRenderNodeRole, BatchHandlerQuad, ProgramManager), RenderSteps (addRenderStep) and Extern. Use for GLSL, fragment shaders, procedural backgrounds, Shadertoy ports, CRT, scanline, distortion or outline effects, or a shader on many sprites. Corrects v3 habits: pipelines, setPipeline, PostFXPipeline, the pipeline config and Shadertoy auto-uniforms don't exist in v4. Triggers on: shader, GLSL, uniform, custom filter, pipeline, render node, render step.
Capabilities
Quick start
In Canvas, this.add.shader() throws, this.renderer.renderNodes is undefined, and enableFilters() does nothing…
Which tool
Each Shader ends the current batch and is a draw call of its own
Shader Game Object
Textures in the textures list go in texture units by index
Shader additions
GLSL can have #pragma phaserTemplate(key) lines, which additions fill
Getting started
Full instructionsInstall 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
Custom rendering: shaders, custom filters and render nodes
How to run your own GLSL in Phaser 4: a Shader Game Object, a custom filter, a custom render node or a RenderStep. All of it is WebGL only.
Source: src/gameobjects/shader/, src/filters/Controller.js, src/renderer/webgl/renderNodes/, src/renderer/webgl/ProgramManager.js, src/renderer/webgl/shaders/, src/gameobjects/components/RenderSteps.js; the guides in docs/Phaser 4 Shader Guide/ and docs/Phaser 4 Rendering Concepts/. Built-in uniforms, template points, default additions and node roles: REFERENCE.md. Related: filters-and-postfx, masks-and-stencils, v3-to-v4-migration.
Quick start
create ()
{
// WebGL only. Phaser.AUTO falls back to Canvas when WebGL fails (4.3+).
if (this.renderer.type !== Phaser.WEBGL)
{
return;
}
const { width, height } = this.scale;
this.add.shader({
name: 'Rainbow',
fragmentSource: `
#pragma phaserTemplate(shaderName)
precision mediump float;
uniform float uTime;
varying vec2 outTexCoord;
void main ()
{
vec3 color = 0.5 + 0.5 * cos(uTime + outTexCoord.xyx + vec3(0.0, 2.0, 4.0));
gl_FragColor = vec4(color, 1.0);
}
`,
setupUniforms: (setUniform) => setUniform('uTime', this.game.loop.getDuration())
}, width / 2, height / 2, width, height);
}
In Canvas, this.add.shader() throws, this.renderer.renderNodes is undefined, and enableFilters() does nothing, so obj.filters stays null.
Which tool
| You want | Use |
|---|---|
| Blur, glow, color matrix, wipe, gradients, noise | Built-in filters (filters-and-postfx) or the Gradient and Noise objects (v4-new-features). Check these first |
| Generated pixels in a rectangle: background, plasma, Shadertoy port | Shader Game Object |
| Change what an object or Camera drew: CRT, distortion, color grade, outline | Custom filter |
| A different shader on many sprites, still batched | Custom BatchHandler render node |
| Code around one object's draw, such as a different DrawingContext | RenderStep |
| A different DrawingContext for a group of objects | CustomContext (masks-and-stencils) |
Raw gl calls, or a 3D library |
Extern |
Each Shader ends the current batch and is a draw call of its own. Each active filter adds a framebuffer and a draw call. A render node keeps batching.
Shader Game Object
this.add.shader(config, x, y, width, height, textures). The defaults are 0, 0, 128, 128, origin 0.5. config can be a shader cache key, which becomes { fragmentKey: key }.
Config key (ShaderQuadConfig) |
Meaning |
|---|---|
name |
Names the render node, and the program unless shaderName is set. Default 'ShaderQuad' |
shaderName |
Base name of the compiled program |
fragmentSource, vertexSource |
Inline GLSL. Used before fragmentKey, vertexKey |
fragmentKey, vertexKey |
Keys in this.cache.shader, from this.load.glsl(key, url) |
initialUniforms |
{ uName: value }, set once |
setupUniforms |
(setUniform, drawingContext) => {}, every render |
shaderAdditions |
[{ name, additions: { templateKey: glsl }, tags?, disable? }] |
updateShaderConfig |
(drawingContext, gameObject, renderNode) => {}, every render, before setupUniforms |
- Leave out the vertex shader. Phaser sets
uProjectionMatrixand gives the fragment shadervarying vec2 outTexCoord, 0 to 1 across the quad, with y = 0 at the bottom. Nothing else is automatic: notime,resolution,mouseoriChannel0. - With no fragment source, or a
fragmentKeynot in the cache, you get the default fragment shader: a UV gradient with template points. No warning. - Methods:
setUniform(name, value)(kept until changed),getUniform(name),setTextures(keys)(replaces the list),setTextureCoordinates(...),setTextureCoordinatesFromFrame(frame)(for an atlas frame),setRenderToTexture(key?),renderImmediate(). - It has a transform, origin, depth, blend mode, scroll factor and size, so it can be tweened, put in a Container, made interactive and given filters. It has no alpha, tint or lighting:
setAlphadoes nothing, so fade it with a uniform. this.load.glsl(key, url)stores aPhaser.Display.BaseShaderwith the source in.glsl. One shader per file: v3 bundles aren't split up.
Textures in the textures list go in texture units by index. Set each sampler uniform to its unit:
this.add.shader({
name: 'Ripple',
fragmentSource: `
#pragma phaserTemplate(shaderName)
precision mediump float;
uniform sampler2D uImage;
uniform float uTime;
varying vec2 outTexCoord;
void main ()
{
vec2 uv = outTexCoord + vec2(sin(outTexCoord.y * 20.0 + uTime * 3.0) * 0.01, 0.0);
gl_FragColor = texture2D(uImage, uv);
}
`,
initialUniforms: { uImage: 0 },
setupUniforms: (setUniform) => setUniform('uTime', this.game.loop.getDuration())
}, this.scale.width / 2, this.scale.height / 2, 256, 256, [ 'logo' ]);
Shader additions
GLSL can have #pragma phaserTemplate(key) lines, which additions fill. The default fragment shader's main is vec4 fragColor = vec4(outTexCoord.xyx, 1.0);, the fragmentProcess point, then gl_FragColor = fragColor;:
this.add.shader({
name: 'Stripes',
shaderAdditions: [ {
name: 'Stripes',
additions: {
fragmentHeader: 'uniform float uTime;',
fragmentProcess: 'fragColor.rgb *= step(0.5, fract(outTexCoord.x * 10.0 + uTime));'
}
} ],
setupUniforms: (setUniform) => setUniform('uTime', this.game.loop.getDuration())
}, this.scale.width / 2, this.scale.height / 2, 400, 300);
additionsis an object of template key to GLSL, not an array. Additions go in in list order, into the vertex and fragment shaders wherever the key appears. Unused template lines are removed.shaderNamebecomes#define SHADER_NAME <program key>.featuresgets#define FEATURE_<NAME>for eachprogramManager.addFeature(name).- To switch additions at run time, use
updateShaderConfigandrenderNode.programManager: setaddition.disable, orgetAddition,addAddition,replaceAddition,removeAddition. - The program cache key is the base name plus the names of the enabled additions. If you change an addition's GLSL, rename it.
Render to a texture
shader.setRenderToTexture('plasmaTexture') draws into a new texture instead of the screen, and ignores the position. Use the key like any texture. While the Shader is on the display list it redraws every frame; off it, call shader.renderImmediate(). For an occasional copy, draw it into a DynamicTexture: dynamic.clear().draw(shader).render().
Custom filters
A filter takes the image of an object or Camera as a texture and draws a new one. It needs two classes, joined by a node name:
- A Controller,
extends Phaser.Filters.Controller, callingsuper(camera, 'NodeName'). It holds the settings. - A render node,
extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader, callingsuper('NodeName', manager, fragmentKey, fragmentSource, shaderAdditions). Passnullas the key when you pass the source.
class Scanlines extends Phaser.Filters.Controller
{
constructor (camera, strength = 0.25)
{
super(camera, 'FilterScanlines');
this.strength = strength;
}
}
const scanlinesFrag = `
#pragma phaserTemplate(shaderName)
precision mediump float;
uniform sampler2D uMainSampler;
uniform vec2 uResolution;
uniform float uStrength;
varying vec2 outTexCoord;
void main ()
{
vec4 color = texture2D(uMainSampler, outTexCoord);
float line = 0.5 + 0.5 * sin(outTexCoord.y * uResolution.y * 3.1416);
gl_FragColor = vec4(color.rgb * (1.0 - uStrength * line), color.a);
}
`;
class FilterScanlines extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader
{
constructor (manager)
{
super('FilterScanlines', manager, null, scanlinesFrag);
}
setupUniforms (controller, drawingContext)
{
this.programManager.setUniform('uResolution', [ drawingContext.width, drawingContext.height ]);
this.programManager.setUniform('uStrength', controller.strength);
}
}
// In create(), after the WebGL guard. The manager belongs to the game, so register once.
const nodes = this.renderer.renderNodes;
if (!nodes.hasNode('FilterScanlines'))
{
nodes.addNodeConstructor('FilterScanlines', FilterScanlines);
}
this.cameras.main.filters.external.add(new Scanlines(this.cameras.main));
const ship = this.add.image(this.scale.width / 2, this.scale.height / 2, 'ship').enableFilters();
ship.filters.internal.add(new Scanlines(ship.filterCamera, 0.5));
Or register it in the game config, which is also safe in Canvas: render: { renderNodes: { FilterScanlines } }.
uMainSampler(unit 0) is the input and is set for you. InsetupUniforms,drawingContextis the output, padding included.- The node's hooks run in this order:
setupTextures(controller, textures, drawingContext),updateShaderConfig(controller, drawingContext),setupUniforms(controller, drawingContext). - More textures: in
setupTextures, settextures[1] = controller.glTextureand the sampler uniform to1. A whole texture's WebGL texture isscene.textures.getFrame(key).glTexture, as insrc/filters/Displacement.js. - You can't change the vertex shader. It gives
outTexCoord(the input) andoutFragCoord(0 to 1 across the output). controller.setActive(false)skips a filter.list.remove(controller)destroys it.- For several passes, extend
BaseFilterand writerun(controller, inputDrawingContext, outputDrawingContext, padding), which runs other filter nodes and returns the output context. SeeFilterBlur.js.
Padding
The output is the size of the input, so whatever you draw past the edges, such as an outline or glow, is cut off. paddingOverride defaults to a zero Rectangle.
controller.setPaddingOverride(left, top, right, bottom)takes edge offsets:(-16, -16, 16, 16)adds 16 pixels on every side.(16, 16, 16, 16)shifts the image and adds nothing.setPaddingOverride(null)clears it.- To work it out from your settings, set
this.paddingOverride = nullin the constructor and overridegetPadding:
getPadding ()
{
if (this.paddingOverride)
{
return this.paddingOverride;
}
const t = Math.ceil(this.thickness);
return this.currentPadding.setTo(-t, -t, t * 2, t * 2);
}
- In the padding,
outTexCoordis outside 0 to 1 andtexture2Dsmears the edge pixels. Put#pragma phaserTemplate(fragmentHeader)after your uniforms and sample withboundedSampler(uMainSampler, uv), which BaseFilterShader adds there and which is transparent outside 0 to 1. - Read padding in your own
runwithcontroller.getPaddingCeil()(4.1), notgetPadding().
Custom render nodes
this.renderer.renderNodes is the RenderNodeManager: one per game, shared by every Scene. Nodes can't be removed.
addNodeConstructor(name, Class)registers a class, made withnew Class(manager)the first timegetNode(name)asks.addNode(name, node)registers one you made. Both throw if the name is taken.getNode(name)returns the node ornull.hasNode(name)checks.render: { renderNodes: { Name: Class } }in the game config registers at boot. A top-levelrenderNodesworks too.
Game Objects use nodes by role. obj.setRenderNodeRole(role, nodeOrName, data?, copyData?) sets one, and null puts the default back. Image, Sprite, Text and Video have Submitter, BatchHandler, Transformer and Texturer. Defaults are in obj.defaultRenderNodes, and the other objects' roles in REFERENCE.md.
To put a shader on many sprites, extend BatchHandlerQuad and add a shader addition. This keeps batching, multi-texturing, tint and lighting:
class BatchHandlerGray extends Phaser.Renderer.WebGL.RenderNodes.BatchHandlerQuad
{
constructor (manager)
{
super(manager, { name: 'BatchHandlerGray' });
this.gray = 1;
// Adds to the default additions. A shaderAdditions config would replace them all.
this.programManager.addAddition({
name: 'Grayscale',
additions: {
fragmentHeader: 'uniform float uGray;',
fragmentProcess: 'fragColor.rgb = mix(fragColor.rgb, vec3(dot(fragColor.rgb, vec3(0.2126, 0.7152, 0.0722))), uGray);'
}
});
}
setupUniforms (drawingContext)
{
super.setupUniforms(drawingContext);
this.programManager.setUniform('uGray', this.gray);
}
}
// After registering it, as for a filter:
sprite.setRenderNodeRole('BatchHandler', 'BatchHandlerGray');
this.renderer.renderNodes.getNode('BatchHandlerGray').gray = 0.5; // Every object using the node
sprite.setRenderNodeRole('BatchHandler', null); // Back to the default
- Your addition goes last, so
fragColoris already textured, tinted and lit, with premultiplied alpha. - Uniforms belong to the node and are shared by every object it draws. For a different value per object, register another node under another name. Objects on different nodes don't batch together.
- If you replace
fragmentSourceinstead, your shader must pick the texture fromuMainSampler[TEXTURE_COUNT]byoutTexDatum, as the default does. A singleuniform sampler2D uMainSampler;only works onBatchHandlerQuadSingle, which draws one quad per draw call. - To see which nodes run, call
renderNodes.setDebug(true)once. It records the next frame, thenrenderNodes.debugToString()returns the tree, such as inthis.renderer.once(Phaser.Renderer.Events.POST_RENDER, ...).
RenderSteps
Each Game Object draws through the functions in obj._renderSteps. Each step must call the next. A new object's list is [ renderWebGL ], which draws the object and calls no next step. enableFilters() inserts its step just before renderWebGL (4.2+), setCleanAlpha() just before the filters step, and Stencil and CustomContext at index 0.
obj.addRenderStep(fn, index):
- Index
0runs first, outside the filters. Use it to change the DrawingContext the finished object goes into. - Index
obj._renderSteps.indexOf(obj.renderWebGL)runs last, inside the filter framebuffer. CallenableFilters()before, or its step goes after yours. - With no index, the step goes after
renderWebGL, so it never runs.
function clipToBox (renderer, gameObject, drawingContext, parentMatrix, renderStep, displayList, displayListIndex)
{
const box = gameObject.clipBox;
const context = box ? drawingContext.getClone() : drawingContext;
if (box)
{
context.setScissorBox(box.x, box.y, box.width, box.height); // Pixels from the top left
context.use();
}
gameObject.renderWebGLStep(renderer, gameObject, context, parentMatrix, renderStep + 1, displayList, displayListIndex);
if (box)
{
context.release();
}
}
sprite.clipBox = new Phaser.Geom.Rectangle(100, 100, 200, 150);
sprite.addRenderStep(clipToBox, 0);
- Steps are called without
this: use thegameObjectargument. - Skipping
renderWebGLStep(..., renderStep + 1, ...)skips the draw. - There is no
removeRenderStep. Turn a step off with a property, asclipBoxdoes. - A cloned DrawingContext doesn't clear.
use()it before drawing andrelease()it after. Its setters includesetBlendMode,setScissorBox,setStencil,setColorWritemaskandsetAlphaStrategy.
Raw WebGL: Extern
Don't call renderer.gl from game code: Phaser tracks GL state and won't see your changes. An Extern finishes the batch, calls your render, then restores Phaser's state:
const extern = this.add.extern();
extern.render = (renderer, drawingContext, calcMatrix) =>
{
// Bind the context's framebuffer, so filters on the Extern work
renderer.glWrapper.updateBindingsFramebuffer({ bindings: { framebuffer: drawingContext.framebuffer } }, true);
// Your gl calls, or a 3D library's render
};
Not in Phaser 4
The full tables are in v3-to-v4-migration.
| v3 | v4 |
|---|---|
PostFXPipeline, setPostPipeline, postFX, preFX |
A custom filter |
MultiPipeline subclass, setPipeline('Name') |
A BatchHandler node and setRenderNodeRole('BatchHandler', 'Name') |
pipeline game config, renderer.pipelines.add |
render.renderNodes, renderNodes.addNodeConstructor |
Shader auto-uniforms, setChannel0, setSampler2D |
Set every uniform yourself; setTextures plus sampler uniforms |
| Texture y = 0 at the top | y = 0 at the bottom, as in WebGL |
Gotchas
- Unknown uniforms are ignored silently: typos, and uniforms the compiler removed because they're unused. For a uniform array, set
'uName[0]'to a flat array. - Colors are premultiplied. Textures sample premultiplied and the NORMAL blend is
ONE, ONE_MINUS_SRC_ALPHA. Outputvec4(rgb * a, a). gl_FragCoordis flipped in framebuffers (filters, render to texture) compared with the canvas. UseoutTexCoord.- Declare
precision mediump float;in every fragment shader you write, or WebGL 1 won't compile it. - Register a node before it's used. A filter with an unregistered node throws when it renders.
setRenderNodeRolewith an unknown name does nothing. Built-in names such asFilterWipeandBatchHandlerQuadare taken, so prefix yours. - Don't
newa BatchHandler increate(). Its GPU buffers and listeners are never freed, andcreate()runs on every restart. Register it and usegetNode. this.game.loop.timeloses precision in a shader. UsegetDuration()(seconds) or wrap it.- Alpha strategies (
render.alphaStrategy, a Stencil's) are ignored by custom shaders unless they handle them.obj.filtersForceComposite = true, afterenableFilters(), draws the object through a Phaser shader which does. render.skipUnreadyShaders: truemeans a new shader draws nothing until it has compiled.- The Shader Guide has errors.
updateShaderConfiggets(drawingContext, gameObject, renderNode), not(gameObject, drawingContext, renderNode). An addition's GLSL is ataddition.additions.fragmentHeader, andadditionsis an object, not a{ key, value }array.
Explore more skills
Browse all- scenesPhaser 4 Scenes: the lifecycle (init, preload, create, update), the Scene config, this.scene (start, restart, launch,…
- camerasPhaser 4 cameras: this.cameras (CameraManager) and this.cameras.main; scroll, zoom, rotation, bounds and worldView;…
- Audio and SoundSound and music in Phaser 4 with the Sound Manager (this.sound): this.sound.play for one-shot effects, this.sound.add…
- Game Setup and ConfigCreate and configure a Phaser 4 game: new Phaser.Game, the GameConfig and its typedefs, the renderer type and the AUTO…
- Time and TimersPhaser 4 time: the Scene Clock (this.time), delayedCall, addEvent and the TimerEvent config (delay, repeat, loop,…
- tweensPhaser 4 tweens: this.tweens.add and this.add.tween, property values (relative, random, arrays, from/to, per-property…
Security
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 →Frequently asked questions about custom-rendering
What does the custom-rendering skill do?
Write your own WebGL rendering in Phaser 4: the Shader Game Object (this.add.shader, ShaderQuadConfig, #pragma phaserTemplate, setupUniforms, shader additions, setRenderToTexture), custom filters (a Phaser.Filters.Controller plus a BaseFilterShader render node, addNodeConstructor, padding), custom render nodes (render.renderNodes, setRenderNodeRole, BatchHandlerQuad, ProgramManager), RenderSteps (addRenderStep) and Extern. Use for GLSL, fragment shaders, procedural backgrounds, Shadertoy ports, CRT, scanline, distortion or outline effects, or a shader on many sprites. Corrects v3 habits: pipelines, setPipeline, PostFXPipeline, the pipeline config and Shadertoy auto-uniforms don't exist in v4. Triggers on: shader, GLSL, uniform, custom filter, pipeline, render node, render step. 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 custom-rendering skill?
Run `npx @skills-hub-ai/cli install phaser-custom-rendering` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/phaser-custom-rendering/ 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 custom-rendering work with?
custom-rendering 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 custom-rendering 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 custom-rendering after installing it?
In Claude Code, type `/phaser-custom-rendering` (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 custom-rendering 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.
[](https://skills-hub.ai/skills/phaser-custom-rendering)<a href="https://skills-hub.ai/skills/phaser-custom-rendering"><img src="https://skills-hub.ai/api/badges/skill/phaser-custom-rendering" alt="Install on Skills Hub"></a>More options in the badge docs.