如图所示的效果,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas-fabric</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// requestAnimationFrame兼容性
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60)
}
})()
// 获取画布,设置全屏
var canvas = document.getElementById('canvas');
// 给它设置宽高并且随浏览器变化而变化, 使用闭包
var w,h;
(function setWidthHeight() {
window.onresize = arguments.callee;
w = window.innerWidth;
h = window.innerHeight;
canvas.width = w;
canvas.height = h;
canvas.style.background = '#090909';
})();
// 找绘画区域
var canCon = canvas.getContext('2d');
// 定义雨滴对象
class Drop {
constructor() {}
init () {
// 横坐标
this.x = random(0, w);
// 纵坐标
this.y = 0;
// this.y改变的基准,即下落速度
this.vy = random(2,3);
// 雨滴下落的最大高度
this.l = random(0.8*h, 0.9*h);
// 波纹的半径,初始为1
this.r = 1;
// 半径扩大的速度
this.vr = 1;
// 判断雨滴消失的透明度
this.a = 1;
this.va = 0.96; // 透明度系数
}
// 画出来
draw () {
// 当雨滴下落到指定位置时,需要开始画圆
if(this.y > this.l) {
canCon.beginPath() // 再次画之前,要把笔先拿起来
canCon.arc(this.x, this.y, this.r, 0, Math.PI*2,false);
canCon.strokeStyle = "rgba(255,255,255,"+ this.a +")";
canCon.stroke(); // 笔没有提起来
} else {
canCon.fillStyle = '#fff';
canCon.fillRect(this.x, this.y, 2, 10);
}
// 动起来
this.update()
}
// 动起来
update () {
// 更新坐标位置
if (this.y < this.l) {
this.y += this.vy;
} else {
if (this.a > 0.03) {
this.r += this.vr
if (this.r > 25) {
this.a *= this.va
}
} else {
this.init()
}
}
}
}
// 实例化
var drops = []
for(var i = 0; i < 50; i++) {
setTimeout(function(){
var drop = new Drop()
drop.init()
drops.push(drop)
},i * 350)
}
// 生成随机数的方法
function random (min,max) {
return Math.random()*(max-min) + min;
}
function move() {
// 重绘
// canCon.clearRect(0,0,w,h);
// 使用透明层叠加实现渐变
canCon.fillStyle = "rgba(0,0,0,0.1)";
canCon.fillRect(0,0,w,h);
for(var j = 0; j < drops.length; j++) {
drops[j].draw()
}
requestAnimationFrame(move)
}
move();
</script>
</body>
</html>