Three.js 水位模拟、水体 Shader、罐体液位动态变化(水箱、水池、储罐液位)

前言

水务组态里储罐、水池是高频组件,需求一般是:

  1. 液位高度根据实时数据动态升降(0~100%)
  2. 水面有轻微波纹扰动,不呆板
  3. 水位颜色区分:正常、告警高液位、低液位
  4. 液位可以和管线连通,搭配流光动画

⚠️ 避坑:

  • 不要用多个 Box 拼水,缩放 Y 轴最省事;
  • 水面波纹尽量写在 FragmentShader,不用顶点动画(顶点多了卡);
  • 液位 Mesh 一定要独立,方便单独控制高度、颜色,不影响罐体外壳。

一、最简方案:缩放实现液位(项目最常用,性能最好)

罐体外壳是固定 Mesh,水体是独立 Mesh,通过 scale.y 或者直接修改 position + 高度,控制水位。

适合方形水池、立式圆筒储罐。

复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>储罐液位</title>
<style>*{margin:0;padding:0}canvas{display:block}</style>
</head>
<body>
<script type="importmap">
{
  "imports": {
    "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene()
scene.background = new THREE.Color(0xf4f4f4)
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200)
camera.position.set(6,7,6)
const renderer = new THREE.WebGLRenderer({antialias:true})
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.outputColorSpace = THREE.SRGBColorSpace
document.body.appendChild(renderer.domElement)
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const ambient = new THREE.AmbientLight(0xffffff,0.5)
const dirLight = new THREE.DirectionalLight(0xffffff,0.7)
dirLight.position.set(5,10,5)
scene.add(ambient,dirLight)
scene.add(new THREE.GridHelper(20,20))

// 储罐外壳(圆筒)
const tankGeo = new THREE.CylinderGeometry(1.8,1.8,6,32)
const tankMat = new THREE.MeshStandardMaterial({color:0xaaaaaa, transparent:true, opacity:0.7})
const tank = new THREE.Mesh(tankGeo, tankMat)
tank.position.y = 3
scene.add(tank)

// 水体:圆柱体,高度和罐体一致,通过scale.y控制液位
const waterGeo = new THREE.CylinderGeometry(1.7,1.7,6,32)
const waterMat = new THREE.MeshStandardMaterial({color:0x3388ff, transparent:true, opacity:0.7})
const water = new THREE.Mesh(waterGeo, waterMat)
water.position.y = 3
scene.add(water)

// 液位设置函数:ratio 0~1
function setWaterLevel(ratio){
  ratio = THREE.MathUtils.clamp(ratio, 0, 1)
  water.scale.y = ratio
  // 缩放之后,水体中心同步偏移,保证底部贴罐底
  water.position.y = ratio * 3
}
// 测试:液位从0到1循环
let level = 0
const clock = new THREE.Clock()
function animate(){
  requestAnimationFrame(animate)
  controls.update()
  const t = clock.getElapsedTime()
  level = (Math.sin(t*0.3)+1)/2
  setWaterLevel(level)
  renderer.render(scene,camera)
}
animate()
window.addEventListener('resize',()=>{
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})
</script>
</body>
</html>

✅ 优点:性能极高、逻辑简单、后端数据直接映射 0~1

⚠️ 缺点:水面是平的,没有波纹,适合对效果要求不高的页面

二、进阶:水体 Shader + 水面波纹(大屏推荐)

在上面基础上,把水体材质换成 ShaderMaterial,水面增加正弦扰动波纹,同时支持液位高度、颜色切换。

原理:用时间 + uv 做多层正弦噪声,模拟细碎水波;液位依然靠 scale.y 控制,Shader 只负责水面效果。

复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>波纹水体Shader液位</title>
<style>*{margin:0;padding:0}canvas{display:block}</style>
</head>
<body>
<script type="importmap">
{
  "imports": {
    "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene()
scene.background = new THREE.Color(0xf4f4f4)
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200)
camera.position.set(6,7,6)
const renderer = new THREE.WebGLRenderer({antialias:true})
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.outputColorSpace = THREE.SRGBColorSpace
document.body.appendChild(renderer.domElement)
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const ambient = new THREE.AmbientLight(0xffffff,0.5)
const dirLight = new THREE.DirectionalLight(0xffffff,0.7)
dirLight.position.set(5,10,5)
scene.add(ambient,dirLight)
scene.add(new THREE.GridHelper(20,20))

// 储罐外壳
const tankGeo = new THREE.CylinderGeometry(1.8,1.8,6,32)
const tankMat = new THREE.MeshStandardMaterial({color:0xaaaaaa, transparent:true, opacity:0.7})
const tank = new THREE.Mesh(tankGeo, tankMat)
tank.position.y = 3
scene.add(tank)

// 水体Shader
const waterShader = {
  uniforms:{
    uTime:{value:0},
    uWaterColor:{value:new THREE.Color(0x2288dd)},
    uWaveSpeed:{value:0.6},
    uWaveStrength:{value:0.04}
  },
  vertexShader:`
    varying vec2 vUv;
    varying vec3 vNormal;
    void main(){
      vUv = uv;
      vNormal = normal;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
  `,
  fragmentShader:`
    uniform float uTime;
    uniform vec3 uWaterColor;
    uniform float uWaveSpeed;
    uniform float uWaveStrength;
    varying vec2 vUv;
    float noise(vec2 p){
      return sin(p.x*6.0 + uTime*uWaveSpeed) * sin(p.y*6.0 + uTime*uWaveSpeed);
    }
    void main(){
      float n = noise(vUv) * uWaveStrength;
      vec3 col = uWaterColor + vec3(n);
      gl_FragColor = vec4(col, 0.72);
    }
  `
}
const waterGeo = new THREE.CylinderGeometry(1.7,1.7,6,32)
const waterMat = new THREE.ShaderMaterial({
  uniforms:waterShader.uniforms,
  vertexShader:waterShader.vertexShader,
  fragmentShader:waterShader.fragmentShader,
  transparent:true
})
const water = new THREE.Mesh(waterGeo, waterMat)
water.position.y = 3
scene.add(water)

// 设置液位
function setWaterLevel(ratio){
  ratio = THREE.MathUtils.clamp(ratio,0,1)
  water.scale.y = ratio
  water.position.y = ratio * 3
}
// 液位告警切换颜色
function setWaterAlarm(isAlarm){
  if(isAlarm){
    waterMat.uniforms.uWaterColor.value.set('#ff4444')
  }else{
    waterMat.uniforms.uWaterColor.value.set('#2288dd')
  }
}

const clock = new THREE.Clock()
let levelRatio = 0.5
function animate(){
  requestAnimationFrame(animate)
  controls.update()
  const t = clock.getElapsedTime()
  levelRatio = (Math.sin(t*0.25)+1)/2 * 0.85 + 0.05
  setWaterLevel(levelRatio)
  waterMat.uniforms.uTime.value = t
  renderer.render(scene,camera)
}
animate()
window.addEventListener('resize',()=>{
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})
</script>
</body>
</html>

参数说明:

  • uWaveSpeed:波纹流动速度,0.4~0.8
  • uWaveStrength:波纹起伏幅度,0.02~0.06,不要太大,不然失真
  • uWaterColor:正常蓝、高液位告警红、低液位橙

三、方形水池、清水池适配

方形水池把 CylinderGeometry 换成 BoxGeometry 即可:

复制代码
const waterGeo = new THREE.BoxGeometry(4,4,4)

缩放逻辑完全一样,uv 自动适配,波纹 Shader 不用改。

四、Vue3 封装 TankLiquid 储罐液位组件(可直接对接后端)

复制代码
<template></template>
<script setup>
import { ref, watch, onUnmounted } from 'vue'
import * as THREE from 'three'
const props = defineProps({
  height: {type:Number, default:6}, // 罐体总高度
  radius: {type:Number, default:1.8},
  level: {type:Number, default:0.4}, // 0~1
  isAlarm: {type:Boolean, default:false},
  waveEnable: {type:Boolean, default:true}
})
let tankMesh = null
let waterMesh = null
let waterMat = null
const clock = new THREE.Clock()

const waterShader = {
  uniforms:{
    uTime:{value:0},
    uWaterColor:{value:new THREE.Color('#2288dd')},
    uWaveSpeed:{value:0.6},
    uWaveStrength:{value:0.04}
  },
  vertexShader:`
    varying vec2 vUv;
    void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}
  `,
  fragmentShader:`
    uniform float uTime;uniform vec3 uWaterColor;
    uniform float uWaveSpeed;uniform float uWaveStrength;
    varying vec2 vUv;
    float noise(vec2 p){
      return sin(p.x*6.0 + uTime*uWaveSpeed)*sin(p.y*6.0 + uTime*uWaveSpeed);
    }
    void main(){
      float n = noise(vUv)*uWaveStrength;
      vec3 col = uWaterColor + vec3(n);
      gl_FragColor = vec4(col,0.72);
    }
  `
}

function createTank(){
  // 罐体
  const tankGeo = new THREE.CylinderGeometry(props.radius, props.radius, props.height, 32)
  const tankMat = new THREE.MeshStandardMaterial({color:0xaaaaaa, transparent:true, opacity:0.7})
  tankMesh = new THREE.Mesh(tankGeo, tankMat)
  tankMesh.position.y = props.height / 2

  // 水体
  const waterGeo = new THREE.CylinderGeometry(props.radius-0.1, props.radius-0.1, props.height, 32)
  if(props.waveEnable){
    waterMat = new THREE.ShaderMaterial({
      uniforms:waterShader.uniforms,
      vertexShader:waterShader.vertexShader,
      fragmentShader:waterShader.fragmentShader,
      transparent:true
    })
  }else{
    waterMat = new THREE.MeshStandardMaterial({color:0x2288dd, transparent:true, opacity:0.7})
  }
  waterMesh = new THREE.Mesh(waterGeo, waterMat)
  waterMesh.position.y = props.height / 2
  setLevel(props.level)
}

function setLevel(ratio){
  ratio = THREE.MathUtils.clamp(ratio,0,1)
  waterMesh.scale.y = ratio
  waterMesh.position.y = ratio * props.height / 2
}
watch(()=>props.level, val=>setLevel(val))
watch(()=>props.isAlarm, (val)=>{
  if(!waterMat) return
  if(props.waveEnable){
    waterMat.uniforms.uWaterColor.value.set(val ? '#ff4444' : '#2288dd')
  }else{
    waterMat.color.set(val ? '#ff4444' : '#2288dd')
  }
})

function renderLoop(){
  requestAnimationFrame(renderLoop)
  if(props.waveEnable && waterMat){
    waterMat.uniforms.uTime.value = clock.getElapsedTime()
  }
}
createTank()
renderLoop()

onUnmounted(()=>{
  if(tankMesh) tankMesh.geometry.dispose()
  if(waterMesh) waterMesh.geometry.dispose()
  if(waterMat) waterMat.dispose()
})
</script>

五、液位联动业务规则(水务常用)

  • level < 0.1:低液位告警,橙色

  • level > 0.85:高液位告警,红色

  • 0.1~0.85:正常蓝色

  • 液位变化加缓动 Tween,不要直接跳变,观感更顺滑

    import { Tween } from 'three/addons/libs/tween.module.js'
    new Tween({r:oldRatio}).to({r:newRatio},600)
    .onUpdate(v=>setLevel(v.r)).start()

六、常见坑

  1. 缩放 Y 之后水体上下错位:同步修改 position.y,保证水体底部贴罐底
  2. 波纹太密 / 太乱:降低 sin 里面的系数,降低 uWaveStrength
  3. 罐体和水体重叠闪烁(Z-fighting):水体半径比罐体小一点点(radius-0.1)
  4. 大量储罐:ShaderMaterial 可以共用 uniform,减少资源开销
  5. 透明水体渲染顺序:透明物体尽量后渲染,或者设置 renderOrder
相关推荐
NendoZen24 分钟前
Bubble Tea V2构建Go TUI应用教程
开发语言·golang·xcode
pan_junbiao1 小时前
Go 语言变量的声明与初始化
开发语言·javascript·golang
泡海椒1 小时前
Java 生成接口调用量趋势 PDF:jquick-pdf 多重折线图(JChartType.MultipleLine)落地
java·开发语言·pdf
syf0611132 小时前
Java 多线程编程:从原理到实战
java·开发语言
code2cat2 小时前
React Native页面导航:编辑任务后,详情页为什么能显示新标题
javascript·react native·react.js
map_3d_vis2 小时前
百度地图自定义控件与右键菜单 ContextMenu
前端·javascript·地图·百度地图
敲上瘾11 小时前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
Thanks_ks14 小时前
JavaScript 事件循环机制详解:同步任务、微任务与宏任务的执行顺序
javascript·promise·前端面试·async/await·事件循环·宏任务·微任务