代码
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 class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="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>
作者:daydreammoon
链接:https://www.jianshu.com/p/ef8ed2385658
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦