Three.js 闪电效果
闪电shader
const shader = new THREE.ShaderMaterial({
uniforms: {
iTime: this.iTime,
color: { value: new THREE.Color("#D2F8FE") },
},
vertexShader: /* glsl */ `
varying vec2 vUv;
varying float normalizeY;
void main() {
// vUv = (uv * 2. - 2.) * vec2(0.3,2.);
vUv = (uv * 2. - 1.) * vec2(1.,1.);
normalizeY = uv.y;
vec3 transformed = position ;
gl_Position = projectionMatrix * modelViewMatrix * vec4(transformed, 1.0);
}
`,
fragmentShader: /* glsl */ `
varying vec2 vUv;
uniform float iTime;
uniform vec3 color;
varying float normalizeY;
// ${fbm}
${perlinFbm}
void main() {
vec3 finalColor = vec3( 0.0 );
for( int i=1; i < 4; ++i ){
float t = abs( 1.0 / ( ( vUv.x + fbm2( vUv + iTime / float( i ) ,5) ) * 75. ) );
// float t = abs( 1.0 / ( ( vUv.x + fbm( vUv + iTime / float( i ) ) ) * 75. ) );
finalColor += t * vec3( float( i ) * 0.1 + 0.1, 0.5, 2.0 );
}
finalColor = pow( finalColor, vec3( 1.4 ) );
vec3 color = vec3( finalColor ) * color;
float fade = smoothstep( 0.0, 0.2, ( 1.0 - normalizeY ) * 1. );
float timeLine = fract( iTime - 0.1 ) * 2. ;
float process = 1.0 - min( timeLine * 3. , 1.);
float a = step( process , normalizeY ) * fade;
// float a = step( process , normalizeY ) ;
if( timeLine > 1.3){
a = step( normalizeY , 1.0 - min( (timeLine / 2. - 0.65) * 4. , 1.) );
}
gl_FragColor = vec4( color, finalColor.r * a );
// gl_FragColor = vec4(vec3(fade), 1.);
// gl_FragColor = vec4(vec3(color), 1);
// if(finalColor.r * a < 0.1){
// discard;
// }
}
`,
transparent: true,
});
const perlinFbm = `
float hash21(vec2 x) {
return fract(cos(mod(dot(x, vec2(13.9898, 8.141)), 3.14)) * 43758.5453);
}
vec2 hash22(vec2 uv) {
uv = vec2(dot(uv, vec2(127.1,311.7)),
dot(uv, vec2(269.5,183.3)));
return 2.0 * fract(sin(uv) * 43758.5453123) - 1.0;
}
float perlinNoise(vec2 uv)
{
vec2 iuv = floor(uv);
vec2 fuv = fract(uv);
vec2 blur = smoothstep(.0, 1., fuv);
vec2 bl = vec2(.0, .0);
vec2 br = vec2(1., .0);
vec2 tl = vec2(.0, 1.);
vec2 tr = vec2(1., 1.);
vec2 bln = hash22(iuv + bl);
vec2 brn = hash22(iuv + br);
vec2 tln = hash22(iuv + tl);
vec2 trn = hash22(iuv + tr);
float b = mix(dot(bln, fuv - bl), dot(brn, fuv - br), blur.x);
float t = mix(dot(tln, fuv - tl), dot(trn, fuv - tr), blur.x);
float c = mix(b, t, blur.y);
return (c);
}
float fbm2(vec2 uv, int octaves)
{
float value = .0;
float ampitude = .5;
float freq = 2. ;
for(int i = 0; i < octaves; i++)
{
value += perlinNoise(uv) * ampitude;
uv *= freq;
ampitude *= .5;
}
return value;
}
`;