效果如下
存储每个星星对象
绘制单个星星,内圆和外圆点的连线
绘制一堆星星
更新星星位置
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>流星</title>
<style>
html,
body {
margin: 0;
padding: 0;
}
#canvas {
background-color: rgba(0,0,0,1);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
window.addEventListener("load", function () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var arr = [];//存储星星
window.addEventListener("resize", resizeFn)
function resizeFn() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeFn();
canvas.style.cssText = `
position: fixed;
z-index: 1000;
pointer-events: none;
`;
setInterval(() => {
arr.push({
x: canvas.width - Math.floor(Math.random() * canvas.width),
y: 0,
r: Math.random() * 2.5 + 2.5,//星星内圆半径
td: Math.random() * 5,//旋转角度
dx: 8,//x轴移动距离
dy: 8,//y轴移动距离
rot: Math.random() * 90 + 90,// 初始的旋转角度
color: "yellow"
});
},50)
// 绘制单个星星
function single(x, y, r, l, rot) {
ctx.beginPath();
// 循环5次,因为5个点
for (let i = 0; i < 5; i++) {
//先绘制小圆上一个点
ctx.lineTo(Math.cos((18 + i * 72 - rot) * Math.PI / 180) * r + x,
-Math.sin((18 + i * 72 - rot) * Math.PI / 180) * r + y);
//连线到大圆上一个点
ctx.lineTo(Math.cos((54 + i * 72 - rot) * Math.PI / 180) * l + x
, -Math.sin((54 + i * 72 - rot) * Math.PI / 180) * l + y);
}
ctx.closePath();
}
// 绘制一堆星星
function draw() {
//循环数组
for (let i = 0; i < arr.length; i++) {
let temp = arr[i];
//调用绘制一个星星函数
single(temp.x, temp.y, temp.r, temp.r * 2, temp.rot);
//星星颜色
ctx.fillStyle = temp.color;
//星星边框颜色
ctx.strokeStyle = temp.color;
//线宽度
ctx.lineWidth = 0.1;
//角有弧度
ctx.lineJoin = "round";
// 填充
ctx.fill();
// 绘制路径
ctx.stroke();
}
}
function update(){
//循环数组
for (let i = 0; i < arr.length; i++) {
arr[i].x -= arr[i].dx;
arr[i].y += arr[i].dy;
arr[i].rot += arr[i].td;
if(arr[i].r < 0) arr.splice(i,1);
}
}
setInterval(() => {
//清屏
ctx.fillStyle = "rgba(0,0,0,0.1)";
ctx.fillRect(0,0,canvas.width, canvas.height);
draw();
update();
})
})
</script>
</body>
</html>