原生JavaScript实现Canvas小鱼游动特效:从零构建高性能交互式动画
在网页设计中,动态效果往往能显著提升用户体验。本文将带你从零开始,用原生JavaScript和Canvas API实现一个高性能的小鱼游动特效,包含3条智能游动的鱼儿与水面波浪的交互效果。不同于依赖jQuery等库的传统实现,我们将专注于原生代码的性能优化与模块化设计。
1. Canvas动画基础与环境搭建
Canvas是HTML5提供的绘图API,它通过JavaScript直接在网页上绘制图形。相比DOM操作,Canvas更适合实现复杂的动画效果,因为它避免了频繁的重排和重绘。
首先创建基础HTML结构:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小鱼游动特效</title>
<style>
#fish-container {
width: 100%;
height: 200px;
position: fixed;
bottom: 0;
left: 0;
z-index: -1;
opacity: 0.4;
}
</style>
</head>
<body>
<div id="fish-container"></div>
<script src="fish-animation.js"></script>
</body>
</html>
关键CSS设置说明:
-
position: fixed使动画固定在窗口底部 -
z-index: -1确保内容显示在动画上方 -
opacity控制透明度实现水纹效果
2. 核心动画架构设计
我们采用面向对象的方式组织代码,主要包含三个核心类:
class FishAnimation {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.container.appendChild(this.canvas);
// 初始化参数
this.fishes = [];
this.surfacePoints = [];
this.animationId = null;
this.lastTimestamp = 0;
// 绑定事件
window.addEventListener('resize', this.handleResize.bind(this));
this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
this.init();
}
init() {
this.setCanvasSize();
this.createSurface();
this.createFishes();
this.startAnimation();
}
// 其他方法将在后续章节实现...
}
2.1 性能优化关键参数
| 参数名 | 默认值 | 说明 |
|---|---|---|
| FISH_COUNT | 3 | 鱼的数量 |
| POINT_INTERVAL | 5 | 水面波浪点间隔(像素) |
| WAVE_DA |

&spm=1001.2101.3001.5002&articleId=102166603&d=1&t=3&u=51aef3243baa4e2cb93f435d2d90269e)
2031

被折叠的 条评论
为什么被折叠?



