这里我直接放在了app下面,因为我就下3秒。要一直下的建议换个位置哈。
<div id="app"></div>
<canvas id="canvas" style="position: absolute;top: 0;"></canvas>
纯js代码实现:
var width = window.innerWidth; //获取系统显示宽度;
var height = window.innerHeight; //获取系统显示高度;
var canvas = document.querySelector("#canvas");
var context = canvas.getContext("2d");
var snowArray = []; //声明一个数组,用于存放创建出来的雪花对象;
canvas.width = width; //设置画布的宽度为系统显示宽度;
canvas.height = height; //设置画布的高度为系统显示高度;
cartoon(); //调用动画;
class Snowflake {
constructor() {
this.init();
}
/**
* @description: 雪花位置
* @return void
*/
init() {
this.position = {
x: Math.random() * width, //x坐标随机;
y: Math.random() * height, //y坐标随机;
} //雪花对象的位置;
this.speed = Math.random() * 10; //雪花下落速度为0-10以内的随机数;
this.r = Math.random() * 6; //雪花的半径为0-6以内的随机数;
this.transparency = Math.random(); //设置雪花的透明度为随机;
this.color = {
r1: Math.random() * 255,
g: Math.random() * 255,
b: Math.random() * 255,
} //雪花颜色随机;
}
/**
* @description: 绘制雪花
* @return void
*/
draw() {
this.position.y++; //y坐标每次递增1像素;
this.transparency -= 0.005; //透明度每次递减0.05;
if (this.transparency <= 0) {
// this.init();
} //雪花透明度小于0,要循环下学就再次调用init()
context.beginPath(); //开始一个新的图形绘制;
context.fillStyle = "rgba(" + this.color.r1 + "," + this.color.g + "," + this.color.b + "," + this.transparency + ")"; //根据类模型绘制圆形雪花;
context.arc(this.position.x, this.position.y, this.r, 0, Math.PI * 2); //填充雪花的颜色;
context.fill();
}
}
for (var i = 0; i < 1225; i++) {
var snow = new Snowflake(); //实例化雪花对象;
snowArray.push(snow); //将雪花对象添加到数组中;
}
/**
* @description: 开启动画
* @return void
*/
function cartoon() {
context.clearRect(0, 0, width, height); //动画完成一次进行清屏操作;
for (var j = 0; j < snowArray.length; j++) {
snowArray[j].draw(); //将实例化好的每个雪花对象在画布上画出来;
}
var requestId = requestAnimationFrame(cartoon); //递归调用动画效果;
if (requestId > 200) {
cancelAnimationFrame(requestId)
//删掉画布
var self = document.getElementById('canvas');
var parent = self.parentElement;
var removed = parent.removeChild(self);
}
}
我这里设置的是雪花融化(不透明)就消失,并在3秒后移除这个画布。
如果想要一直下雪的,把雪花消失注释掉的init()放出来,requestId > 200不删掉画布就好了。