Phaser 3 Black and White or Greyscale Sprites

Stephen Garside | Tue 28 Apr 20 > 2 min read

Wondering how you can make individual Phaser 3 game sprites black and white or greyscale? - Its easy with pipelines, a custom shader and a few lines of simple code. 

This article does not explain what custom shaders are, for that I recommend reading this excellent article on phaser 3 custom shaders, which helped me understand what they are and how they are built. Essentially a shader is just a function that is applied to each individual pixel at render time.

Phaser 3 has the setTint function on each sprite, but all this does is add a colour tint to the sprite. Here is an example of a coloured sprite with a dark grey tint (0x363636) applied:

You can still see colour, and the character starts to disappear on darker backgrounds, so the setTint function is not an option.

Phaser 3 Black And White Grayscale Sprites (1)

Phaser 3 Black and White or Greyscale Sprite Shader

Phaser 3 introduced Render Pipelines, which can be created and applied to cameras, sprites and images.  The first step in creating a black and white sprite is to create a greyscale pipeline and register it with the game renderer.  Here is the code:

const GrayscalePipeline = new Phaser.Class({
        Extends: Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline,
        initialize:
            function GrayscalePipeline(game) {
                Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline.call(this, {
                game: game,
                renderer: game.renderer,
                fragShader: `
                precision mediump float;
                uniform sampler2D uMainSampler;
                varying vec2 outTexCoord;
                void main(void) {
                vec4 color = texture2D(uMainSampler, outTexCoord);
                float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
                gl_FragColor = vec4(vec3(gray), 1.0);
                }`
            });
        }
    });
    
this.game.renderer.addPipeline('Grayscale', new GrayscalePipeline(this.game));

You only need to create and register a custom pipeline / shader once in a game, so I tend to do this in an init scene.

The final step is to associate the pipeline to the sprite / image:

const blackAndWhiteSprite = this.add.sprite(400, 300, 'yourSpriteImageKey').setPipeline('Grayscale');

To remove the pipeline from the sprite is as easy as:

blackAndWhiteSprite.resetPipeline();

This is the final result, a nice and clear sprite with a greyscale pipeline shader applied:

That is all there is to it! A nice easy example of how to make individual images and sprites black and white or greyscale in Phaser 3 games.

If you found this article useful, why not read my other Phaser 3 game blog posts.

Leave Your Comments...