当前位置: 首页 > news >正文

Three.js 着色器光效教程

着色器光效 ·Shader Light· ▶ 在线运行案例

  • 案例合集:三维可视化功能案例(threehub.cn)
  • 开源仓库github地址:https://github.com/z2586300277/three-cesium-examples
  • 400个案例代码:网盘链接

你将学到什么

  • ShaderMaterial 自定义着色器实现核心视觉效果
  • OrbitControls 相机轨道交互
  • Canvas 动态纹理贴图
  • requestAnimationFrame渲染循环与resize自适应

效果说明

本案例演示着色器光效效果:用 Canvas 2D 绘制内容并实时映射为 Three.js 纹理;核心用到 ShaderMaterial、OrbitControls、Canvas。建议先打开文首在线案例查看动态画面,再对照下方源码逐步理解。

核心概念

  • Scene / Camera / WebGLRenderer构成最小渲染闭环;大场景可开logarithmicDepthBuffer缓解 Z-fighting。
  • ShaderMaterial通过uniforms+ 自定义 GLSL 控制逐像素/逐点效果;透明粒子常配合depthTest: false
  • OrbitControls提供轨道旋转/缩放;开启enableDamping后需在 animate 中controls.update()
  • CanvasTexture每帧或按需把 2D Canvas 内容上传 GPU,适合动态文字、图表、视频帧贴图。

实现步骤

  • 搭建 Scene、PerspectiveCamera、WebGLRenderer,挂载 canvas 并处理resize
  • 定义 uniforms / onBeforeCompile 或 ShaderMaterial,编写 GLSL 与材质参数
  • 创建 OrbitControls(及 Raycaster 等交互控件,若源码包含)
  • requestAnimationFrame循环中更新状态并 render(Cesium 为viewer.render或自动渲染)
  • 代码要点

    import * as THREE from 'three'

    import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

    let scene, camera, renderer, controls let fakeLights = [] const clock = new THREE.Clock()

    init() animate()

    function init() { scene = new THREE.Scene() scene.background = new THREE.Color('#0a0a1a')

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 ) camera.position.set(0, 15, 30)

    renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }) renderer.setSize(window.innerWidth, window.innerHeight) renderer.setPixelRatio(window.devicePixelRatio) document.body.appendChild(renderer.domElement)

    controls = new OrbitControls(camera, renderer.domElement) controls.enableDamping = true createFakeLights() }

    function createGlowTexture(color) { const canvas = document.createElement('canvas') canvas.width = 256 canvas.height = 256 const ctx = canvas.getContext('2d')

    const gradient = ctx.createRadialGradient(128, 128, 0, 128, 128, 128) gradient.addColorStop(0, color) gradient.addColorStop(0.3, color.replace('1)', '0.6)')) gradient.addColorStop(0.6, color.replace('1)', '0.2)')) gradient.addColorStop(1, color.replace('1)', '0)'))

    ctx.fillStyle = gradient ctx.fillRect(0, 0, 256, 256)

    const texture = new THREE.CanvasTexture(canvas) texture.needsUpdate = true return texture }

    function createFakeLight(position, color, size) { const group = new THREE.Group()

    const glowTexture = createGlowTexture(color)

    const coreMaterial = new THREE.ShaderMaterial({ uniforms: { uTexture: { value: glowTexture }, uOpacity: { value: 1.0 }, uTime: { value: 0 } }, vertexShader:varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrixmodelViewMatrixvec4(position, 1.0); }, fragmentShader:uniform sampler2D uTexture; uniform float uOpacity; uniform float uTime; varying vec2 vUv;

    void main() { vec4 texColor = texture2D(uTexture, vUv); float pulse = 0.8 + 0.2sin(uTime2.0); gl_FragColor = vec4(texColor.rgb, texColor.auOpacitypulse); }, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide })

    const coreGeometry = new THREE.PlaneGeometry(size, size) const core = new THREE.Mesh(coreGeometry, coreMaterial) core.position.copy(position) core.lookAt(camera.position) group.add(core)

    for (let i = 1; i <= 3; i++) { const layerMaterial = coreMaterial.clone() layerMaterial.uniforms.uOpacity.value = 0.3 / i const layerGeometry = new THREE.PlaneGeometry(size(1 + i0.5), size(1 + i0.5)) const layer = new THREE.Mesh(layerGeometry, layerMaterial) layer.position.copy(position) layer.position.y -= i * 0.1 layer.lookAt(camera.position) group.add(layer) }

    return { group, core, material: coreMaterial } }

    function createFakeLights() { const lightConfigs = [ { pos: new THREE.Vector3(-10, 5, -10), color: 'rgba(255, 100, 100, 1)', size: 8 }, { pos: new THREE.Vector3(10, 5, -10), color: 'rgba(100, 255, 100, 1)', size: 8 }, { pos: new THREE.Vector3(0, 8, 10), color: 'rgba(100, 100, 255, 1)', size: 10 }, { pos: new THREE.Vector3(-15, 3, 5), color: 'rgba(255, 200, 100, 1)', size: 6 }, { pos: new THREE.Vector3(15, 3, 5), color: 'rgba(255, 100, 200, 1)', size: 6 } ]

    lightConfigs.forEach(config => { const fakeLight = createFakeLight(config.pos, config.color, config.size) scene.add(fakeLight.group) fakeLights.push(fakeLight) }) }

    function animate() { requestAnimationFrame(animate)

    const elapsed = clock.getElapsedTime()

    fakeLights.forEach(fakeLight => { fakeLight.material.uniforms.uTime.value = elapsed fakeLight.core.lookAt(camera.position) })

    controls.update() renderer.render(scene, camera) }

    完整源码:GitHub

    小结

    • 本文提供着色器光效完整 Three.js 源码与在线 Demo,建议先运行案例再改 uniform/参数做二次实验
    • 更多 Three.js 实战案例见 three-cesium-examples 合集 与 GitHub 开源仓库
http://www.jsqmd.com/news/1150904/

相关文章:

  • 高精度ADC ADS122U04与MK24FN256VDC12的工业测量系统设计
  • 数据库自然语言交互的上下文管理:多轮对话中的Schema感知与意图识别
  • 3款图像分割标注工具对比:QuPath vs LabelMe vs CVAT,标注效率实测分析
  • 平价正宗重庆火锅实测|理性避坑选型指南
  • 苹果18硬件升级:本地AI开发与高性能计算实践指南
  • AI 短剧生产:一天踩了 10 个坑(Seedance 2.0 + TOS + 火山方舟填坑实录)
  • 机器学习 7 大范式实战对比:Scikit-learn 代码实现与 3 大核心差异解析
  • 3大音乐平台逐字歌词完整解决方案:ESLyric-LyricsSource完全指南
  • OpenCV 与 imutils 四点透视变换对比:3种答题卡区域提取方案性能实测
  • 【大数据毕业设计】基于多源旅游数据的景区热度分析与推荐系统的设计与实现 基于 Django 的旅游偏好挖掘与景区推荐系统(源码+文档+远程调试,全bao定制等)
  • 深夜调参的决策树:什么时候该停,什么时候该换方向
  • 音乐解锁终极指南:5分钟掌握全平台加密音乐解密技术
  • 如何在Windows上运行安卓应用?5个技巧让你告别笨重模拟器
  • Unity WebGL部署Apache Tomcat:MIME配置、Gzip压缩与缓存优化实战
  • 中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
  • 决策树分类实战:Sklearn API 调参 5 要点,泰坦尼克号预测准确率 0.82
  • 锂离子电池组主动平衡技术解析与BQ25887应用实践
  • OpenCV 4.8 图像傅里叶变换实战:3种滤波器(低通/高通/带通)性能对比与代码实现
  • 如何5分钟掌握CS2智能库存管理:开源工具CASEMOVE终极指南
  • LV3296与PIC18F4515的高精度数据采集方案
  • 自适应AI视觉系统实战:清华AdaptiveNN架构解析与PyTorch 2.0复现
  • Kubernetes监控部署指南
  • 图像去雾 3 大流派实战对比:增强、恢复、融合方法在 RESIDE 数据集上的 PSNR/SSIM 评测
  • Keras 与 OpenCV 人脸检测对比:95% 准确率模型 vs Haar Cascade 级联分类器
  • 3个关键步骤:在macOS上成功部署SMAPI模组框架的完整指南
  • QuPath 0.7.0 细胞分割实战:5步完成HE染色图像自动标注,IoU提升至0.85
  • 高精度模拟信号采集系统设计与实现:ADS127L11与TM4C1294应用
  • 前端构建工具插件开发与生态
  • 掌握Docker多阶段构建镜像优化技巧
  • 4K 显示器 vs 300 DPI 印刷品:像素密度 (PPI) 的 2 种计算与视觉差异对比