js实现大海
实现海洋动画效果
使用Canvas绘制动态波浪效果是模拟大海的常见方法。以下代码创建了一个带有波浪动画的海洋场景:
const canvas = document.getElementById('oceanCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = 200;
let time = 0;
function animateWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#1a73e8';
ctx.beginPath();
const waveHeight = 20;
const waveLength = 0.01;
for(let x = 0; x < canvas.width; x++) {
const y = canvas.height/2 + Math.sin(x * waveLength + time) * waveHeight;
ctx.lineTo(x, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.fill();
time += 0.05;
requestAnimationFrame(animateWave);
}
animateWave();
添加3D海洋效果
使用Three.js可以创建更逼真的3D海洋场景。需要先引入Three.js库:
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();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const waterGeometry = new THREE.PlaneGeometry(100, 100, 128, 128);
const water = new THREE.Water(waterGeometry, {
textureWidth: 512,
textureHeight: 512,
waterNormals: new THREE.TextureLoader().load('waternormals.jpg'),
sunDirection: new THREE.Vector3(),
sunColor: 0xffffff,
waterColor: 0x0077be,
distortionScale: 3.7
});
scene.add(water);
function animate() {
requestAnimationFrame(animate);
water.material.uniforms.time.value += 0.01;
renderer.render(scene, camera);
}
animate();
使用CSS实现简单海浪
纯CSS也可以创建基础的波浪效果,适合性能要求不高的场景:
.ocean {
position: relative;
height: 100px;
background: linear-gradient(to bottom, #0077be, #00a1ff);
overflow: hidden;
}
.wave {
position: absolute;
bottom: 0;
width: 200%;
height: 100px;
background-repeat: repeat no-repeat;
background-position: 0 bottom;
background-size: 50% 100px;
animation: wave 7s linear infinite;
}
@keyframes wave {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
添加海洋生物元素
增强真实感可以添加游动的鱼类或其他海洋生物:
function createFish() {
const fish = document.createElement('div');
fish.className = 'fish';
fish.style.left = `${Math.random() * 100}%`;
fish.style.top = `${60 + Math.random() * 30}%`;
fish.style.animationDuration = `${5 + Math.random() * 10}s`;
document.querySelector('.ocean').appendChild(fish);
}
for(let i=0; i<10; i++) {
createFish();
}
优化性能的技巧
大规模海洋动画可能消耗较多资源,可以采用以下优化方法:
- 限制动画帧率到30fps
- 使用离屏Canvas预渲染静态元素
- 对3D场景使用适当的LOD(细节层次)控制
- 在移动设备上降低波浪的顶点数量
这些方法可以根据具体需求组合使用,从简单CSS动画到复杂3D渲染都能实现不同细节程度的海洋效果。







