效果图
代码
dot.js
/*
* @Author: likang xie
* @Date: 2018-05-23 16:01:21
* @Purpose: Dot粒子类
*/
class Dot {
constructor(x, y, vx, vy) {
this.x = x; // x坐标
this.y = y; // y坐标
this.vx = vx; // x速度
this.vy = vy; // y速度
this.size = Math.ceil(Math.random() * 2); // 随机大小
this.speed = 1; // 整体定时器的帧率,越大越快
}
// 初始化粒子
render() {
ctx.save();
ctx = ctx;
ctx.beginPath();
ctx.fillStyle = 'lightgray';
ctx.arc(this.x - this.size / 2, this.y - this.size / 2, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// 更新粒子(坐标位置)
update() {
this.x = this.x + this.vx * this.speed;
this.y = this.y + this.vy * this.speed;
this.vx = (this.x < canvas.width && this.x > 0) ? this.vx : (-this.vx);
this.vy = (this.y < canvas.height && this.y > 0) ? this.vy : (-this.vy);
this.render();
}
}
dot.html
<!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>dot</title>
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
background-color: rgba(0, 0, 0, .6);
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="dot"></canvas>
<script src="dot.js" type="text/javascript" charset="utf-8"></script>
<script>
// 一些变量
let num = 500; // 粒子的数量
let dots = []; // 存储所有粒子的一个数组
let duration = [1, -1]; // 粒子默认的前进方向,后面会随机取值
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
// 设置canvas的大小
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
// 随机生成num个粒子
for (let i = 0; i < num; i++) {
// 随机x,y坐标、vx方向的速度,vy方向的速度
let x = Math.ceil(Math.random() * canvas.width);
let y = Math.ceil(Math.random() * canvas.height);
let d = duration[Math.floor(Math.random() * duration.length)];
let vx = Math.ceil(Math.random() * 1) * d;
let vy = Math.ceil(Math.random() * 2) * d;
let dot = new Dot(x, y, vx, vy);
dot.render();
dots.push(dot);
// 3s之后粒子整体移动速率变为0.1,让我装一下
setTimeout(() => {
dot.speed = .1;
}, 3000);
}
// 移动
requestAnimationFrame(move);
function move() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < num; i++) {
dots[i].update();
}
requestAnimationFrame(move);
}
</script>
</body>
</html>
最后
本文到此结束,希望以上内容对你有些许帮助,如若喜欢请记得点个赞
跟关注
哦 💨
微信公众号
「前端宇宙情报局」
,将不定时更新最新、实用的前端技巧/技术性文章,欢迎关注,一起学习 🌘