How to use shader in Cocos2d-JS-v3.0-alpha

var HelloWorldLayer = cc.Layer.extend({
    sprite:null,
    ctor:function ()
    {
        this._super();
        var size = cc.director.getWinSize();
        this.sprite = cc.Sprite.create(res.HelloWorld_png);
        this.sprite.attr({
            x: size.width / 2,
            y: size.height / 2,
            scale: 0.5,
            rotation: 180
        });
        this.addChild(this.sprite, 0);
        graySprite(this.sprite);                       
        return true;
    }
});

function graySprite(sprite)
{
    if(sprite)
    {
        var shader = new cc.GLProgram();//cc.GLProgram.create("gray.vsh", "gray.fsh");
        shader.retain();
        //shader.initWithByteArrays("res/gray.vsh", "res/gray.fsh");
        shader.initWithFilenames("res/gray.vsh", "res/gray.fsh");
        shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
        shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
        shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
    
        shader.link();
        shader.updateUniforms();
        sprite.setShaderProgram(shader);
    }    
}


gray.fsh.zip (0.3 KB)


gray.vsh.zip (0.3 KB)

Hi, does this work on canvas or is it WebGL only?

Hi yuye
this code Can’t Runing Cocos2d-JS-v2.x Can you provide a right

1 Like

@z104207 you can reference here

@yuye my cocos2d-js is Cocos2d-JS-v3.0-alpha2, but use your code didn’t run correct, the screen is black but could see fps,why?

Just a note for the future reader. In cocos2d-js3.0 cc.Sprite.create(res.HelloWorld_png) when later loads the texture changes the shaderProgram back to the default.
A solution could be to set the shader with a sprite.addLoadedEventListener(…)

1 Like

I know this is an old topic, but I found this code and was also getting a black screen when running this shader.
The problem is in the vertex shader. The gl_Position must be calculated as follows:
gl_Position = CC_PMatrix * CC_MVMatrix * a_position;