html 结构
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
}
#canvas{
display:block;
background-color:#000;
}
</style>
</head>
<body>
<canvas id="canvas" width="" height=""></canvas>
</body>
</html>
js代码
let canvas = document.getElementById('canvas');
//定义画布宽高 所需的变量
let ctxWidth;
let ctxHeight;
//根据浏览器窗口的的改变 实时改变canvas画布的宽高
window.onresize = function(){
rSize();
}
rSize()
function rSize(){
ctxWidth = window.innerWidth;
ctxHeight = window.innerHeight;
canvas.width = ctxWidth;
canvas.height = ctxHeight;
}
var ctx = canvas.getContext("2d");
//绘制一个雨滴
// var y = 0;
// setInterval(()=>{
// ctx.fillStyle = "rgba(0,0,0,0.1)"
// ctx.fillRect(0,0,ctxWidth,ctxHeight)
// ctx.fillStyle = 'blue'
// ctx.fillRect(500,y+=10,4,10)
// },100)
//随机数
function random(min,max){
return Math.random() * (max-min) + min;
}
//设置雨滴对象 创建雨滴
class Rain{
constructor(){
}
//初始化
init(){
//雨滴在x轴上的位置 随机的
this.x = random(0,ctxWidth);
//雨滴在y轴上的位置
this.y = 0;
//雨滴在y轴上的移动速度
this.vy = random(5,10);
//雨滴在y轴的停止的位置 整个画布的80%-90%位置停止
this.t = random(0.8*ctxHeight,0.9*ctxHeight)
//圆的半径
this.r = random(1,2);
//圆 半径变化的速度
this.vr = 1;
}
//创建雨滴
esta(){
//当雨滴在y轴上的位置 小于 停止位置时
if(this.y <= this.t){
//绘制矩形
ctx.beginPath()
ctx.fillStyle = '#00FFFF';
ctx.fillRect(this.x,this.y,5,10)
}else{
//绘制圆形
ctx.beginPath()
ctx.strokeStyle = "#00FFFF";
ctx.arc(this.x,this.y,this.r,0*Math.PI/180,Math.PI*2)
ctx.stroke();
}
}
//移动
move(){
//雨滴在y轴上的位置 小于 停止位置时
if(this.y <= this.t){
//继续运动
this.y += this.vy;
}else{
//当圆的半径 小于 100
if(this.r <= 100){
//继续运动
this.r += this.vr;
}else{
//对雨滴进行初始化
this.init();
}
}
//创建雨滴
this.esta();
}
}
//这里只能创建一个雨滴
// var f = new Rain();
// f.init();
// f.esta();
// setInterval(()=>{
// ctx.fillStyle = "rgba(0,0,0,0.03)"
// ctx.fillRect(0,0,ctxWidth,ctxHeight)
// f.move();
// })
//定义一个数组 将雨滴push进数组中
var arrRain = [];
//创建雨滴 根据传进来的参数创建雨滴
function createRain(num){
for(let i = 0; i < num; i++){
//每两百毫秒生成一个雨滴
setTimeout(()=>{
let f = new Rain();
f.init();
f.esta();
//当实例对象 雨滴 储存到数组中
arrRain.push(f)
},200*i)
}
}
createRain(50)
console.log(arrRain)
//让数组中的每一个雨滴进行运动
setInterval(()=>{
//添加矩形 进行覆盖 添加透明颜色 使雨滴看起来有透明的效果
ctx.fillStyle = "rgba(0,0,0,0.15)"
ctx.fillRect(0,0,ctxWidth,ctxHeight)
for(let item of arrRain){
// itme.move();
item.move();
}
},18)