js实现水柱
实现水柱效果的JavaScript方法
使用Canvas绘制动态水柱
创建Canvas元素并设置基础样式:
<canvas id="waterColumn" width="200" height="400"></canvas>
JavaScript实现逻辑:
const canvas = document.getElementById('waterColumn');
const ctx = canvas.getContext('2d');
let waterLevel = 100;
const amplitude = 20;
let phase = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制容器
ctx.strokeStyle = '#333';
ctx.strokeRect(50, 50, 100, 300);
// 创建波浪路径
ctx.beginPath();
ctx.moveTo(50, 150 + waterLevel);
for(let x = 50; x <= 150; x++) {
const y = 150 + waterLevel + Math.sin((x + phase) * 0.1) * amplitude;
ctx.lineTo(x, y);
}
ctx.lineTo(150, 400);
ctx.lineTo(50, 400);
ctx.closePath();
// 填充水柱
const gradient = ctx.createLinearGradient(0, 150, 0, 400);
gradient.addColorStop(0, 'rgba(64, 164, 223, 0.8)');
gradient.addColorStop(1, 'rgba(32, 98, 149, 0.6)');
ctx.fillStyle = gradient;
ctx.fill();
phase += 0.5;
waterLevel = 100 + Math.sin(phase * 0.05) * 30;
requestAnimationFrame(animate);
}
animate();
CSS实现静态水柱效果
通过伪元素创建基础效果:
.water-column {
width: 100px;
height: 300px;
background: linear-gradient(to bottom, #e0f7fa, #80deea);
position: relative;
overflow: hidden;
border: 2px solid #00838f;
}
.water-column::after {
content: '';
position: absolute;
top: 30%;
left: -25%;
width: 150%;
height: 150%;
background: rgba(128, 222, 234, 0.7);
border-radius: 40%;
animation: wave 5s infinite linear;
}
@keyframes wave {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
SVG实现方案
使用SVG路径动画创建更流畅的效果:
<svg width="200" height="400" viewBox="0 0 200 400">
<path id="water" fill="url(#waterGradient)">
<animate attributeName="d"
dur="5s"
repeatCount="indefinite"
values="M0,200 Q50,150 100,200 T200,200 L200,400 L0,400 Z;
M0,220 Q50,190 100,220 T200,220 L200,400 L0,400 Z;
M0,200 Q50,150 100,200 T200,200 L200,400 L0,400 Z"/>
</path>
<linearGradient id="waterGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#4fc3f7"/>
<stop offset="100%" stop-color="#0288d1"/>
</linearGradient>
</svg>
Three.js三维水柱
对于需要3D效果的场景:

import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
const geometry = new THREE.CylinderGeometry(1, 1, 5, 32);
const material = new THREE.MeshPhongMaterial({
color: 0x3399ff,
transparent: true,
opacity: 0.8
});
const cylinder = new THREE.Mesh(geometry, material);
scene.add(cylinder);
const light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(5, 5, 5);
scene.add(light);
function animate() {
requestAnimationFrame(animate);
cylinder.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
性能优化建议
- 对于Canvas实现,使用
requestAnimationFrame而非setInterval - 限制重绘区域而不是清除整个画布
- 对静态元素使用缓存
- 在移动设备上考虑降低波浪细节
- 使用CSS硬件加速属性如
transform和opacity






