本项目是移动端单页

点击打开梦幻动画H5单页

流程

播放音乐

判断浏览器类型,如果禁止自动播放音乐就点击播放

随机初始化气泡位置以及气泡大小

使用 requestAnimationFrame 创建气泡上浮动画

监听气泡是否超出视口

渲染文字

隐藏首屏logo
更换背景
引用 typed.js实现文字打印效果

随机创建流星和落叶,使用 requestAnimationFrame 创建动画

requestAnimationFrame

简介

由于 setTimeout 和 setInterval 的不精准问题,促使了 requestAnimationFrame 的诞生。
requestAnimationFrame 是专门为实现高性能的帧动画而设计的一个API,目前已在多个浏览器得到了支持,你可以把它用在 DOM 上的效果切换或者 Canvas 画布动画中。
requestAnimationFrame 并不是定时器,但和 setTimeout 很相似,在没有 requestAnimationFrame 的浏览器一般都是用 setTimeout 模拟。
requestAnimationFrame 跟屏幕刷新同步(大多数是 60Hz )。如果浏览器支持 requestAnimationFrame , 则不建议使用 setTimeout 来做动画。

requestAnimationFrame 的兼容使用

下面是我们常规使用 requestAnimationFrame 的兼容写法,当浏览器不兼容的 requestAnimationFrame 时则通过使用 setTimeout 来模拟实现,且设定渲染间隔为 1000ms/60。

1
2
3
4
5
6
7
8
9
10
// 判断是否有 requestAnimationFrame 方法,如果有则模拟实现
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 30);
};

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>认识Canvas</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid #33"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// 兼容定义 requestAnimFrame
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 30);
};

// 绘制的圆的对象
var circle = {
x: 250,
y: 250,
radius: 50,
direction: 'right',
// 移动圆形
move: function() {
if (this.direction === 'right') {
if (this.x <= 430) {
this.x += 5;
} else {
this.direction = 'left';
}
} else {
if (this.x >= 60) {
this.x -= 5;
} else {
this.direction = 'right';
}
}
},
draw: function() {
// 绘制圆形
context.beginPath();
// 设置开始角度为0,结束角度为 2π 弧度
context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
context.fillStyle = '#00c09b';
context.fill();
}
}
// 动画执行函数
function animate() {
// 随机更新圆形位置
circle.move();
// 清除画布
context.clearRect(0, 0, canvas.width, canvas.height);
// 绘画圆
circle.draw();
// 使用requestAnimationFrame实现动画循环
requestAnimationFrame(animate);
}

// 先画第一帧的圆,即初始化的圆
circle.draw();
// 执行animate
animate();
</script>
</body>
</html>

本项目参考腾讯课堂-【Next特训班】第五期 梦幻动画 DIY 直播课