‍⚕️主页 gis分享者‍⚕️感谢各位大佬 点赞 收藏⭐ 留言 加关注✅!‍⚕️收录于专栏threejs gis工程师文章目录一、前言1.1 ☘️THREE.ShaderMaterial1.1.1 ☘️注意事项1.1.2 ☘️构造函数1.1.3 ☘️属性1.1.4 ☘️方法二、实现炫酷流动霓虹效果1. ☘️实现思路2. ☘️代码样例一、前言本文详细介绍如何基于threejs在三维场景中实现炫酷流动霓虹效果亲测可用。希望能帮助到您。一起学习加油加油1.1 ☘️THREE.ShaderMaterialTHREE.ShaderMaterial使用自定义shader渲染的材质。 shader是一个用GLSL编写的小程序 在GPU上运行。1.1.1 ☘️注意事项ShaderMaterial 只有使用 WebGLRenderer 才可以绘制正常 因为 vertexShader 和fragmentShader 属性中GLSL代码必须使用WebGL来编译并运行在GPU中。从 THREE r72开始不再支持在ShaderMaterial中直接分配属性。 必须使用BufferGeometry实例使用BufferAttribute实例来定义自定义属性。从 THREE r77开始WebGLRenderTarget 或 WebGLCubeRenderTarget实例不再被用作uniforms。 必须使用它们的texture 属性。内置attributes和uniforms与代码一起传递到shaders。如果您不希望WebGLProgram向shader代码添加任何内容则可以使用RawShaderMaterial而不是此类。您可以使用指令#pragma unroll_loop_start#pragma unroll_loop_end以便通过shader预处理器在GLSL中展开for循环。 该指令必须放在循环的正上方。循环格式必须与定义的标准相对应。循环必须标准化normalized。循环变量必须是i。对于给定的迭代值 UNROLLED_LOOP_INDEX 将替换为 i 的显式值并且可以在预处理器语句中使用。#pragma unroll_loop_startfor(int i0;i10;i){// ...}#pragma unroll_loop_end代码示例constmaterialnewTHREE.ShaderMaterial({uniforms:{time:{value:1.0},resolution:{value:newTHREE.Vector2()}},vertexShader:document.getElementById(vertexShader).textContent,fragmentShader:document.getElementById(fragmentShader).textContent});1.1.2 ☘️构造函数ShaderMaterial( parameters : Object )parameters - (可选)用于定义材质外观的对象具有一个或多个属性。 材质的任何属性都可以从此处传入(包括从Material继承的任何属性)。1.1.3 ☘️属性共有属性请参见其基类Material。.clipping: Boolean定义此材质是否支持剪裁; 如果渲染器传递clippingPlanes uniform则为true。默认值为false。.defaultAttributeValues: Object当渲染的几何体不包含这些属性但材质包含这些属性时这些默认值将传递给shaders。这可以避免在缓冲区数据丢失时出错。this.defaultAttributeValues{color:[1,1,1],uv:[0,0],uv2:[0,0]};.defines: Object使用 #define 指令在GLSL代码为顶点着色器和片段着色器定义自定义常量每个键/值对产生一行定义语句defines:{FOO:15,BAR:true}这将在GLSL代码中产生如下定义语句#defineFOO15#defineBARtrue.extensions: Object一个有如下属性的对象this.extensions{derivatives:false,// set to use derivativesfragDepth:false,// set to use fragment depth valuesdrawBuffers:false,// set to use draw buffersshaderTextureLOD:false// set to use shader texture LOD};.fog: Boolean定义材质颜色是否受全局雾设置的影响; 如果将fog uniforms传递给shader则为true。默认值为false。.fragmentShader: String片元着色器的GLSL代码。这是shader程序的实际代码。在上面的例子中 vertexShader 和 fragmentShader 代码是从DOMHTML文档中获取的 它也可以作为一个字符串直接传递或者通过AJAX加载。.glslVersion: String定义自定义着色器代码的 GLSL 版本。仅与 WebGL 2 相关以便定义是否指定 GLSL 3.0。有效值为 THREE.GLSL1 或 THREE.GLSL3。默认为空。.index0AttributeName: String如果设置则调用gl.bindAttribLocation 将通用顶点索引绑定到属性变量。默认值未定义。.isShaderMaterial: Boolean只读标志用于检查给定对象是否属于 ShaderMaterial 类型。.lights: Boolean材质是否受到光照的影响。默认值为 false。如果传递与光照相关的uniform数据到这个材质则为true。默认是false。.linewidth: Float控制线框宽度。默认值为1。由于OpenGL Core Profile与大多数平台上WebGL渲染器的限制无论如何设置该值线宽始终为1。.flatShading: Boolean定义材质是否使用平面着色进行渲染。默认值为false。.uniforms: Object如下形式的对象{uniform1:{value:1.0},uniform2:{value:2}}指定要传递给shader代码的uniforms键为uniform的名称值(value)是如下形式{value:1.0}这里 value 是uniform的值。名称必须匹配 uniform 的name和GLSL代码中的定义一样。 注意uniforms逐帧被刷新所以更新uniform值将立即更新GLSL代码中的相应值。.uniformsNeedUpdate: Boolean可用于在 Object3D.onBeforeRender() 中更改制服时强制进行制服更新。默认为假。.vertexColors: Boolean定义是否使用顶点着色。默认为假。.vertexShader: String顶点着色器的GLSL代码。这是shader程序的实际代码。 在上面的例子中vertexShader 和 fragmentShader 代码是从DOMHTML文档中获取的 它也可以作为一个字符串直接传递或者通过AJAX加载。.wireframe: Boolean将几何体渲染为线框(通过GL_LINES而不是GL_TRIANGLES)。默认值为false即渲染为平面多边形。.wireframeLinewidth: Float控制线框宽度。默认值为1。由于OpenGL Core Profile与大多数平台上WebGL渲染器的限制无论如何设置该值线宽始终为1。1.1.4 ☘️方法共有方法请参见其基类Material。.clone (): ShaderMaterial this :ShaderMaterial创建该材质的一个浅拷贝。需要注意的是vertexShader和fragmentShader使用引用拷贝 attributes的定义也是如此; 这意味着克隆的材质将共享相同的编译WebGLProgram 但是uniforms 是 值拷贝这样对不同的材质我们可以有不同的uniforms变量。二、实现炫酷流动霓虹效果1. ☘️实现思路通过threejs的ShaderMaterial自定义着色器实现炫酷流动霓虹效果。具体代码参考下面代码样例。2. ☘️代码样例!DOCTYPEHTMLPUBLIC-//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtdhtmlheadmetacharsetUTF-8title炫酷流动霓虹/title!-- Include Three.js --scriptsrchttps://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js/script!-- Include lil-gui for the settings panel --scriptsrchttps://cdn.jsdelivr.net/npm/lil-gui0.19/scriptstylebody{margin:0;padding:0;overflow:hidden;background-color:#000;font-family:sans-serif;}canvas{display:block;width:100vw;height:100vh;}/style/headbody/bodyscript// Support me by PayPal: https://paypal.com/paypalme/sabosugi// --- SCENE SETUP ---constscenenewTHREE.Scene();// Use an Orthographic camera for a 2D full-screen shaderconstcameranewTHREE.OrthographicCamera(-1,1,1,-1,0,1);constrenderernewTHREE.WebGLRenderer({antialias:true,alpha:false});renderer.setSize(window.innerWidth,window.innerHeight);renderer.setPixelRatio(window.devicePixelRatio);document.body.appendChild(renderer.domElement);// --- SHADER MATERIAL ---// Vertex Shader: Simply passes the UV coordinates to the fragment shaderconstvertexShadervarying vec2 vUv; void main() { vUv uv; gl_Position vec4(position, 1.0); };// Fragment Shader: Generates the glowing wavesconstfragmentShaderuniform float uTime; uniform vec2 uResolution; uniform vec3 uColor1; // Primary color (Blue) uniform vec3 uColor2; // Secondary color (Pink) uniform vec3 uBgColor; // Background color uniform float uSpeed; uniform float uComplexity; // Drives the number of mathematical iterations uniform float uDensity; uniform float uIntensity; // Mouse interaction uniforms uniform vec2 uMouse; uniform float uHoverEffect; varying vec2 vUv; // 2D Rotation matrix mat2 rot(float a) { float s sin(a), c cos(a); return mat2(c, -s, s, c); } void main() { // Normalize pixel coordinates vec2 p (gl_FragCoord.xy * 2.0 - uResolution.xy) / min(uResolution.x, uResolution.y); vec2 original_p p; // Store original coordinates for the vignette vec3 finalColor vec3(0.0); float time uTime * uSpeed * 0.5; // Add initial cinematic tilt p * rot(0.2); // --- MOUSE HOVER EFFECT --- if (uHoverEffect 0.0) { // Normalize mouse coordinates to match the screen space vec2 m uMouse; m.x * uResolution.x / min(uResolution.x, uResolution.y); m.y * uResolution.y / min(uResolution.x, uResolution.y); // Apply the same tilt to the mouse coordinates m * rot(0.2); // Calculate distance between pixel and mouse float mouseDist length(p - m); // Use smoothstep for a very soft, bounded area of effect float force smoothstep(1.5, 0.0, mouseDist) * uHoverEffect; // Increased the displacement and twist multipliers to make the effect more visible // while keeping (p - m) to prevent the black hole singularity in the center p (p - m) * force * 0.15; // Increased from 0.03 for a stronger push p * rot(force * 0.12); // Increased from 0.02 for a stronger visible twist } // --- ITERATIVE FUNCTION SYSTEM (Complex Formula) --- // This loop folds space over itself recursively to create high-detail abstract structures. float iterations floor(uComplexity); for (float i 1.0; i 20.0; i) { if (i iterations) break; // Allow dynamic complexity via GUI // Scale and rotate space organically, but more uniformly to keep lines parallel p * rot(sin(time * 0.05) * 0.1 0.08); // --- HARMONIC VORTEX FLUID --- vec2 q p; // 1. Smooth Vortex twist: wider, gentler rotation float dist length(p); q * rot(dist * uDensity * 0.25 - time * 0.3); // 2. Harmonic Folds: Frequencies are mathematically related (1.0x, 2.0x, 0.5x) float freq uDensity * 0.8; // Layer 1 folds (Base frequency, uniform phase shift per iteration) q.x sin(q.y * freq time * 0.5 i * 0.15) * 0.5; q.y cos(q.x * freq - time * 0.5 - i * 0.15) * 0.5; vec2 r q; // Layer 2 ripples (Double frequency, half amplitude for harmony) r.x sin(q.y * freq * 2.0 - time * 0.8) * 0.25; r.y cos(q.x * freq * 2.0 time * 0.8) * 0.25; // Combine into a synchronized, rhythmic ribbon float wave sin(r.x * freq * 1.5 time) * 0.6 cos(r.y * freq * 0.5 - time * 0.7) * 0.4; // Calculate distance to the warped geometric boundary float d abs(r.y - wave); // Complex rendering layer: Hard core dual soft ambient glows float core 0.005 / max(d, 0.002); float soft1 exp(-d * 8.0) * 0.6; float soft2 exp(-d * 2.0) * 0.2; // Dynamic Chromatic Dispersion (Color mapping) float mixFactor sin(r.x * 3.0 r.y * 2.0 time i * 1.6) * 0.5 0.5; vec3 layerColor mix(uColor1, uColor2, mixFactor); // Accumulate lighting using additive blending float attenuation 1.0 / (i * 0.6 1.0); finalColor layerColor * (core soft1 soft2) * uIntensity * attenuation * 30.0; // Fractal zoom for the next iteration (scales the space) p r * 1.05; } // --- POST-PROCESSING --- // 1. Blend with deep background finalColor uBgColor * 0.5; // 2. Cinematic Vignette (darken edges) float vignette 1.0 - smoothstep(0.5, 2.5, length(original_p)); finalColor * vignette; // 3. ACES Filmic HDR Tone Mapping (Approximation) // This prevents the intense glowing colors from washing out into flat white finalColor finalColor * (2.51 * finalColor 0.03) / (finalColor * (2.43 * finalColor 0.59) 0.14); gl_FragColor vec4(finalColor, 1.0); };// Define the uniform variables passed to the shaderconstuniforms{uTime:{value:0.0},uResolution:{value:newTHREE.Vector2(window.innerWidth*window.devicePixelRatio,window.innerHeight*window.devicePixelRatio)},uColor1:{value:newTHREE.Color(#0055ff)},// Electric BlueuColor2:{value:newTHREE.Color(#ff00aa)},// Hot PinkuBgColor:{value:newTHREE.Color(#05030a)},// Very dark violet/blackuSpeed:{value:0.3},uComplexity:{value:8.0},uDensity:{value:3.2535},uIntensity:{value:0.03758},uMouse:{value:newTHREE.Vector2(0,0)},uHoverEffect:{value:0.0}// Disabled by default};constmaterialnewTHREE.ShaderMaterial({vertexShader:vertexShader,fragmentShader:fragmentShader,uniforms:uniforms,depthWrite:false,depthTest:false});// Create a full-screen plane to render the shader onconstgeometrynewTHREE.PlaneGeometry(2,2);constmeshnewTHREE.Mesh(geometry,material);scene.add(mesh);// --- MOUSE TRACKING LOGIC ---// Use a target vector to smoothly interpolate the actual mouse positionconsttargetMousenewTHREE.Vector2(0,0);functionupdateMousePosition(clientX,clientY){// Convert mouse position to normalized device coordinates (-1 to 1)targetMouse.x(clientX/window.innerWidth)*2-1;targetMouse.y-(clientY/window.innerHeight)*21;}window.addEventListener(mousemove,(e){updateMousePosition(e.clientX,e.clientY);});// Support for touch deviceswindow.addEventListener(touchmove,(e){if(e.touches.length0){updateMousePosition(e.touches[0].clientX,e.touches[0].clientY);}},{passive:true});// --- LIL-GUI SETTINGS PANEL ---// State object to hold our GUI valuesconstsettings{speed:0.3,complexity:8,density:3.2535,intensity:0.03758,hoverEffect:false,// Checkbox statecolor1:#0055ff,color2:#ff00aa,bgColor:#05030a};constguinewlil.GUI({title:Shader Settings});// Animation controlsconstanimFoldergui.addFolder(Complex Formula Settings);animFolder.add(settings,speed,0.0,3.0).name(Speed).onChange(vuniforms.uSpeed.valuev);animFolder.add(settings,complexity,1,20,1).name(Math Iterations).onChange(vuniforms.uComplexity.valuev);animFolder.add(settings,density,0.5,5.0).name(Space Folding).onChange(vuniforms.uDensity.valuev);animFolder.add(settings,intensity,0.001,0.05).name(Neon Exposure).onChange(vuniforms.uIntensity.valuev);// Interactive controlsconstinteractiveFoldergui.addFolder(Interaction);interactiveFolder.add(settings,hoverEffect).name(Hover Effect).onChange(v{// Smoothly toggle the uniform value between 0.0 and 1.0uniforms.uHoverEffect.valuev?1.0:0.0;});// Color controlsconstcolorFoldergui.addFolder(Colors);colorFolder.addColor(settings,color1).name(Primary Color).onChange(vuniforms.uColor1.value.set(v));colorFolder.addColor(settings,color2).name(Secondary Color).onChange(vuniforms.uColor2.value.set(v));colorFolder.addColor(settings,bgColor).name(Background Color).onChange(vuniforms.uBgColor.value.set(v));// Collapse the main GUI panel by defaultgui.close();// --- ANIMATION LOOP ---constclocknewTHREE.Clock();functionanimate(){requestAnimationFrame(animate);// Smoothly interpolate the mouse position (Lerp) for a fluid, dragged effectuniforms.uMouse.value.x(targetMouse.x-uniforms.uMouse.value.x)*0.05;uniforms.uMouse.value.y(targetMouse.y-uniforms.uMouse.value.y)*0.05;// Update time uniform for fluid motionuniforms.uTime.valueclock.getElapsedTime();renderer.render(scene,camera);}// --- RESIZE HANDLER ---window.addEventListener(resize,(){// Update renderer sizerenderer.setSize(window.innerWidth,window.innerHeight);// Update resolution uniform for the shaderuniforms.uResolution.value.set(window.innerWidth*window.devicePixelRatio,window.innerHeight*window.devicePixelRatio);});// Start the animation loopanimate();/script/html效果如下源码