原生JS Canvas 小鱼游动特效:350行代码实现3条鱼与水面交互(附源码)

原生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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值