这是一个 HTML5 版本的 Shader 特效,只使用了一张图片就能呈现旗帜飘扬的动画效果,点击【阅读原文】可以在浏览器中预览实际效果。
下面是顶点着色器代码:
代码语言:javascript复制uniform float u_Distance;
attribute vec2 a_Position;
varying vec2 v_UV;
varying float v_Slope;
float PI = 3.14159;
float scale = 0.8;
void main() {
float x = a_Position.x;
float y = a_Position.y;
float amplitude = 1.0 - scale; // 振幅
float period = 2.0; // 周期
float waveLength = 2.0 * scale;
v_UV = (mat3(0.625,0,0, 0,0.625,0, 0.5,0.5,1) * vec3(x, y, 1.0)).xy;
y = amplitude * ( (x - (-scale)) / waveLength) * sin(2.0 * PI * (x - u_Distance));
float x2 = x - 0.001;
float y2 = a_Position.y amplitude * ( (x2 - (-scale)) / waveLength) * sin(2.0 * PI * (x2 - u_Distance));
v_Slope = y - y2;
gl_Position = vec4(vec2(x, y), 0.0, 1.0);
}
这里是片元着色器代码
代码语言:javascript复制precision mediump float;
uniform sampler2D u_Sampler;
varying vec2 v_UV;
varying float v_Slope;
void main() {
vec4 color = texture2D( u_Sampler, v_UV );
if( v_Slope > 0.0 ) {
color = mix( color, vec4(0.0, 0.0, 0.0, 1.0), v_Slope * 300.0 );
}
if( v_Slope < 0.0 ) {
color = mix( color, vec4(1.0), abs(v_Slope) * 300.0 );
}
if(v_UV.x < 0.0 || v_UV.x > 1.0 || v_UV.y < 0.0 || v_UV.y > 1.0) {
color.a = 0.0;
}
gl_FragColor = color;
}