<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Canvas五角星变换特效</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starCanvas"></canvas>
<script>
const canvas = document.getElementById('starCanvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 五角星参数
const stars = [];
const starCount = 50;
const colors = ['#FF5F5F', '#5F9FFF', '#5FFF9F', '#FFD75F', '#D75FFF'];
// 初始化五角星
for (let i = 0; i < starCount; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: 5 + Math.random() * 20,
color: colors[Math.floor(Math.random() * colors.length)],
rotation: Math.random() * Math.PI * 2,
rotationSpeed: (Math.random() - 0.5) * 0.02,
points: 5,
innerRadius: 0.4 + Math.random() * 0.3,
speedX: (Math.random() - 0.5) * 2,
speedY: (Math.random() - 0.5) * 2,
targetPoints: 5,
pulseSpeed: 0.01 + Math.random() * 0.02,
pulseSize: 0.5 + Math.random() * 0.5
});
}
// 绘制五角星函数
function drawStar(x, y, points, innerRadius, outerRadius, color, rotation) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(rotation);
ctx.beginPath();
const angleStep = (Math.PI * 2) / points;
for (let i = 0; i < points * 2; i++) {
const radius = i % 2 === 0 ? outerRadius : innerRadius * outerRadius;
const angle = i * angleStep - Math.PI / 2;
const xPos = radius * Math.cos(angle);
const yPos = radius * Math.sin(angle);
if (i === 0) {
ctx.moveTo(xPos, yPos);
} else {
ctx.lineTo(xPos, yPos);
}
}
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
// 动画循环
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
stars.forEach(star => {
// 更新位置
star.x += star.speedX;
star.y += star.speedY;
// 边界检查
if (star.x < 0 || star.x > canvas.width) star.speedX *= -1;
if (star.y < 0 || star.y > canvas.height) star.speedY *= -1;
// 旋转
star.rotation += star.rotationSpeed;
// 点数变化
if (Math.random() < 0.005) {
star.targetPoints = 3 + Math.floor(Math.random() * 5);
}
if (star.points < star.targetPoints) star.points += 0.05;
if (star.points > star.targetPoints) star.points -= 0.05;
// 脉动效果
const pulse = 1 + Math.sin(Date.now() * star.pulseSpeed) * star.pulseSize;
// 绘制五角星
drawStar(
star.x,
star.y,
star.points,
star.innerRadius,
star.size * pulse,
star.color,
star.rotation
);
});
requestAnimationFrame(animate);
}
// 处理窗口大小变化
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// 开始动画
animate();
</script>
</body>
</html>
706

被折叠的 条评论
为什么被折叠?



