pixijs shader 案例
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=;
// 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 = .; // number boxes
const float s = . / 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 = . - p.y; // Shader Toy
// float t = min( 1., 2. * unTime / unDuration); // one-time
float t = min( ., . * mod(customUniform,0.5*unDuration) / unDuration); // repeat
vec2 b = mod( p, s ); // offset in box
vec2 i = floor( p / s ); // box#
float cells = (.*n - .);
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/.; // how fast first cell turns
rate += n/.; // 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(.,.,.,.);
} 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);
} }