js实现月亮
使用Canvas绘制月亮
在JavaScript中,可以通过HTML5的Canvas API绘制月亮形状。以下是一个简单的实现示例:
const canvas = document.getElementById('moonCanvas');
const ctx = canvas.getContext('2d');
// 绘制满月
ctx.beginPath();
ctx.arc(150, 150, 100, 0, Math.PI * 2);
ctx.fillStyle = '#FDB813';
ctx.fill();
// 绘制月牙(通过叠加圆形实现)
ctx.beginPath();
ctx.arc(170, 150, 100, 0, Math.PI * 2);
ctx.fillStyle = '#000';
ctx.fill();
使用SVG创建月亮
SVG是另一种创建矢量图形的有效方式,适合需要缩放而不失真的场景:
<svg width="300" height="300">
<circle cx="150" cy="150" r="100" fill="#FDB813"/>
<circle cx="170" cy="150" r="100" fill="#000"/>
</svg>
使用CSS绘制月亮
纯CSS也可以实现简单的月亮效果,适合不需要复杂交互的场景:
<div class="moon"></div>
<style>
.moon {
width: 200px;
height: 200px;
background-color: #FDB813;
border-radius: 50%;
position: relative;
}
.moon::after {
content: '';
position: absolute;
width: 200px;
height: 200px;
background-color: #000;
border-radius: 50%;
left: 20px;
}
</style>
使用Three.js创建3D月亮
对于需要3D效果的场景,可以使用Three.js库:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry(5, 32, 32);
const material = new THREE.MeshBasicMaterial({color: 0xFDB813});
const moon = new THREE.Mesh(geometry, material);
scene.add(moon);
camera.position.z = 10;
function animate() {
requestAnimationFrame(animate);
moon.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
添加月相变化效果
通过调整Canvas绘制参数可以实现月相变化:

function drawMoonPhase(ctx, x, y, radius, phase) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = '#FDB813';
ctx.fill();
ctx.beginPath();
ctx.ellipse(x + radius * (1 - phase * 2), y, radius, radius, 0, 0, Math.PI * 2);
ctx.fillStyle = '#000';
ctx.fill();
}






