效果图
dot.gif
代码
- 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;
- // 随机生成 20 个粒子
- 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>
如果您喜欢这篇文章, 那么记得动动你们的, 给个 like 或者关注我哦.
来源: http://www.jianshu.com/p/ef8ed2385658