- 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
- 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
<!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>canvas--随机粒子</title>
<style>
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
background-color:#000;
}
</style>
</head>
<body>
<canvas id='canvas'></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const WIDTH = document.documentElement.clientWidth;
const HEIGHT = document.documentElement.clientHeight;
canvas.width = WIDTH;
canvas.height = HEIGHT;
function Particle(x, y) {
this.symbol = Symbol();
this.x = x;
this.y = y;
this.r = (Math.random() * 20) + 1;
let cr = Math.random() * 256;
let cg = Math.random() * 256;
let cb = Math.random() * 256;
let alpha = (Math.floor(Math.random() * 10) + 1) / 10;
this.color = `rgba(${cr},${cg},${cb},${alpha})`;
}
Particle.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.shadowBlur = this.r * 2;
ctx.fill();
}
Particle.prototype.move = function (step=1.5) {
this.y -= step;
if (this.y <= -10) {
this.y = HEIGHT + 10;
}
this.draw();
}
let arr = [];
function init(len = 100) {
for (let i = 0; i < len; i++) {
arr[i] = new Particle(Math.random() * WIDTH, Math.random() * HEIGHT);
arr[i].draw();
}
animate();
}
function animate() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
arr.forEach(item => {
item.move();
})
requestAnimationFrame(animate);
}
init();
</script>
</body>
</html>