pixijs shader 案例

pixijs shader 案例_pixijs



const app = new PIXI.Application({ transparent: true });
document.body.appendChild(app.view);

// Create background image
const background = PIXI.Sprite.from('/moban/bg_grass.jpg');
background.width = app.screen.width;
background.height = app.screen.height;
app.stage.addChild(background);

// Stop application wait for load to finish
app.stop();

app.loader.add('shader', '/moban/shader.frag')
.load(onLoaded);

let filter;

// Handle the load completed
function onLoaded(loader, res) {
// Create the new filter, arguments: (vertexShader, framentSource)
filter = new PIXI.Filter(null, res.shader.data, {
customUniform: 0.0,
});

// === WARNING ===
// specify uniforms in filter constructor
// or set them BEFORE first use
// filter.uniforms.customUniform = 0.0

// Add the filter
background.filters = [filter];

// Resume application update
app.start();
}
var i=0;
// Animate the filter
app.ticker.add((delta) => {
i+=0.03;

filter.uniforms.customUniform = i;
});



precision mediump float;

varying vec2 vTextureCoord;
varying vec4 vColor;

uniform sampler2D uSampler;
uniform float customUniform;

const float n = 8.; // number boxes
const float s = 1. / n; // box size in texels
const float pi = 3.14159265358979;
const float _90 = 0.5 * pi; // 90 degrees

#define unDuration 10.0
void main(void)
{

vec2 p = vTextureCoord;
p.y = 1. - p.y; // Shader Toy
// float t = min( 1., 2. * unTime / unDuration); // one-time
float t = min( 1., 2. * mod(customUniform,0.5*unDuration) / unDuration); // repeat
vec2 b = mod( p, s ); // offset in box
vec2 i = floor( p / s ); // box#
float cells = (2.*n - 2.);
float delay = (i.x + i.y) / cells;
t -= 0.5*delay;
float a = _90*t; // 90 degrees * t
float rate = (cells - (i.x + i.y)) / cells;
rate *= n/2.; // how fast first cell turns
rate += n/2.; // how fast last cell turns: min 2.0
a *= rate;
a = min( _90, a );
a = max( 0.0, a );
float ca = cos(a);
float sa = sin(a);
const float w = 0.5*s; // half box size in world space
vec2 l = vec2( -w, w ); // pre top-left
vec2 m = vec2( w, w ); // pre top-right
vec2 r = vec2( w, -w ); // pre bot-right
vec2 L = vec2( l.x*ca - l.y*sa, l.x*sa+ l.y*ca );// post top-left
vec2 M = vec2( m.x*ca - m.y*sa, m.x*sa+ m.y*ca );// post top-right
vec2 R = vec2( r.x*ca - r.y*sa, r.x*sa+ r.y*ca ); // post bot-right
float Fx = b.x - w;
if( Fx < M.x ) {
float dx = Fx - L.x;
float dy = tan(a)*dx; // y1-y0=m(x1-x0)
float d = sqrt( (dx*dx) + (dy*dy) );
p.x = i.x*s + d;
gl_FragColor = vec4(0.,0.,0.,0.);
} else { // image2 rotating towards
float ex = Fx - M.x;
float ey = tan(a + _90)*ex;
float e = sqrt( (ex*ex) + (ey*ey) );
p.x = i.x*s + e;
gl_FragColor = texture2D(uSampler,p);
}



}