js实现太阳
使用Canvas绘制太阳动画
以下是一个使用JavaScript和HTML5 Canvas绘制动态太阳效果的实现方法,包含发光效果和简单动画:
<!DOCTYPE html>
<html>
<head>
<title>太阳动画</title>
<style>
body { margin: 0; overflow: hidden; background: #87CEEB; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="sunCanvas"></canvas>
<script>
const canvas = document.getElementById('sunCanvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 太阳属性
const sun = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 100,
rays: 12,
rayLength: 150,
color: '#FFD700',
glowColor: 'rgba(255, 215, 0, 0.5)',
angle: 0,
pulse: 0
};
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制太阳光芒
drawSunGlow();
// 绘制太阳
drawSun();
// 更新动画参数
sun.angle += 0.01;
sun.pulse = Math.sin(sun.angle) * 0.1 + 1;
requestAnimationFrame(animate);
}
function drawSunGlow() {
const gradient = ctx.createRadialGradient(
sun.x, sun.y, sun.radius,
sun.x, sun.y, sun.radius * 3
);
gradient.addColorStop(0, sun.glowColor);
gradient.addColorStop(1, 'rgba(255, 215, 0, 0)');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(sun.x, sun.y, sun.radius * 3, 0, Math.PI * 2);
ctx.fill();
}
function drawSun() {
// 绘制光芒射线
ctx.save();
ctx.translate(sun.x, sun.y);
for (let i = 0; i < sun.rays; i++) {
const angle = (i * (Math.PI * 2 / sun.rays)) + sun.angle;
const x1 = Math.cos(angle) * sun.radius;
const y1 = Math.sin(angle) * sun.radius;
const x2 = Math.cos(angle) * (sun.radius + sun.rayLength * sun.pulse);
const y2 = Math.sin(angle) * (sun.radius + sun.rayLength * sun.pulse);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = 8;
ctx.strokeStyle = sun.color;
ctx.stroke();
}
ctx.restore();
// 绘制太阳主体
ctx.beginPath();
ctx.arc(sun.x, sun.y, sun.radius, 0, Math.PI * 2);
ctx.fillStyle = sun.color;
ctx.fill();
}
// 响应窗口大小变化
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
sun.x = canvas.width / 2;
sun.y = canvas.height / 2;
});
animate();
</script>
</body>
</html>
实现说明
-
画布设置
创建HTML5 Canvas元素并设置其大小为窗口大小,获取2D渲染上下文。 -
太阳属性
定义太阳的各种属性,包括位置、半径、光芒数量、光芒长度、颜色和动画参数。 -
动画循环
使用requestAnimationFrame创建平滑动画,每帧清除画布并重绘太阳。 -
发光效果
使用径向渐变创建太阳的发光效果,从中心向外逐渐淡化。 -
光芒射线
围绕太阳中心绘制多条射线,通过旋转角度和脉冲效果创建动态光芒。 -
响应式设计
监听窗口大小变化事件,调整画布和太阳位置以适应不同屏幕尺寸。
自定义选项
可以修改以下参数来自定义太阳效果:

sun.radius:改变太阳主体大小sun.rays:调整光芒数量sun.rayLength:控制光芒长度sun.color和sun.glowColor:更改颜色方案- 动画速度:调整
sun.angle的增量值
这个实现创建了一个具有脉冲发光效果的动态太阳,光芒会缓慢旋转并轻微伸缩,模拟真实的太阳视觉效果。






