Skip to main content

Build

Custom Rendering

PhaserOfficialCertified

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.

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

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 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

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

js
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 uProjectionMatrix and gives the fragment shader varying vec2 outTexCoord, 0 to 1 across the quad, with y = 0 at the bottom. Nothing else is automatic: no time, resolution, mouse or iChannel0.
  • With no fragment source, or a fragmentKey not 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: setAlpha does nothing, so fade it with a uniform.
  • this.load.glsl(key, url) stores a Phaser.Display.BaseShader with 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:

js
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;:

js
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);
  • additions is 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.
  • shaderName becomes #define SHADER_NAME <program key>. features gets #define FEATURE_<NAME> for each programManager.addFeature(name).
  • To switch additions at run time, use updateShaderConfig and renderNode.programManager: set addition.disable, or getAddition, 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:

  1. A Controller, extends Phaser.Filters.Controller, calling super(camera, 'NodeName'). It holds the settings.
  2. A render node, extends Phaser.Renderer.WebGL.RenderNodes.BaseFilterShader, calling super('NodeName', manager, fragmentKey, fragmentSource, shaderAdditions). Pass null as the key when you pass the source.
js
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. In setupUniforms, drawingContext is 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, set textures[1] = controller.glTexture and the sampler uniform to 1. A whole texture's WebGL texture is scene.textures.getFrame(key).glTexture, as in src/filters/Displacement.js.
  • You can't change the vertex shader. It gives outTexCoord (the input) and outFragCoord (0 to 1 across the output).
  • controller.setActive(false) skips a filter. list.remove(controller) destroys it.
  • For several passes, extend BaseFilter and write run(controller, inputDrawingContext, outputDrawingContext, padding), which runs other filter nodes and returns the output context. See FilterBlur.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 = null in the constructor and override getPadding:
js
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, outTexCoord is outside 0 to 1 and texture2D smears the edge pixels. Put #pragma phaserTemplate(fragmentHeader) after your uniforms and sample with boundedSampler(uMainSampler, uv), which BaseFilterShader adds there and which is transparent outside 0 to 1.
  • Read padding in your own run with controller.getPaddingCeil() (4.1), not getPadding().

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 with new Class(manager) the first time getNode(name) asks. addNode(name, node) registers one you made. Both throw if the name is taken.
  • getNode(name) returns the node or null. hasNode(name) checks.
  • render: { renderNodes: { Name: Class } } in the game config registers at boot. A top-level renderNodes works 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:

js
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 fragColor is 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 fragmentSource instead, your shader must pick the texture from uMainSampler[TEXTURE_COUNT] by outTexDatum, as the default does. A single uniform sampler2D uMainSampler; only works on BatchHandlerQuadSingle, which draws one quad per draw call.
  • To see which nodes run, call renderNodes.setDebug(true) once. It records the next frame, then renderNodes.debugToString() returns the tree, such as in this.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 0 runs 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. Call enableFilters() before, or its step goes after yours.
  • With no index, the step goes after renderWebGL, so it never runs.
js
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 the gameObject argument.
  • Skipping renderWebGLStep(..., renderStep + 1, ...) skips the draw.
  • There is no removeRenderStep. Turn a step off with a property, as clipBox does.
  • A cloned DrawingContext doesn't clear. use() it before drawing and release() it after. Its setters include setBlendMode, setScissorBox, setStencil, setColorWritemask and setAlphaStrategy.

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:

js
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. Output vec4(rgb * a, a).
  • gl_FragCoord is flipped in framebuffers (filters, render to texture) compared with the canvas. Use outTexCoord.
  • 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. setRenderNodeRole with an unknown name does nothing. Built-in names such as FilterWipe and BatchHandlerQuad are taken, so prefix yours.
  • Don't new a BatchHandler in create(). Its GPU buffers and listeners are never freed, and create() runs on every restart. Register it and use getNode.
  • this.game.loop.time loses precision in a shader. Use getDuration() (seconds) or wrap it.
  • Alpha strategies (render.alphaStrategy, a Stencil's) are ignored by custom shaders unless they handle them. obj.filtersForceComposite = true, after enableFilters(), draws the object through a Phaser shader which does.
  • render.skipUnreadyShaders: true means a new shader draws nothing until it has compiled.
  • The Shader Guide has errors. updateShaderConfig gets (drawingContext, gameObject, renderNode), not (gameObject, drawingContext, renderNode). An addition's GLSL is at addition.additions.fragmentHeader, and additions is an object, not a { key, value } array.

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 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.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/phaser-custom-rendering)](https://skills-hub.ai/skills/phaser-custom-rendering)
HTML
<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.