How to set image's grayscale by shader

Hi I wanna set the grayscale of texture monster to 100% and here’s my codes:

import grayscaleGlsl from './gray-scale.glsl.js?url'

// ...
    preload() {
      // ...
      this.load.image(`monster`, monsterInfo.pic)
      this.load.glsl('grayscale', grayscaleGlsl)
    }

    create() {
      this.add.image(100, 100, `monster`)
      this.add.shader('grayscale', 100, 100, 280, 280, [`monster`])
    }

source of gray-scale.glsl.js:

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);
}

But it doesn’t work, a black rectangle covers it unexpectedly.

How to rewrite the glsl.js?

See grayscale() in https://labs.phaser.io/edit.html?src=src/fx\colormatrix\colormatrix%20fx.js.

1 Like