js实现月亮
使用Canvas绘制月亮
在JavaScript中,可以通过HTML5的Canvas API绘制一个月亮。以下是一个简单的实现示例:
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#FDB813'; // 月亮颜色
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2); // 主圆
ctx.fill();
ctx.globalCompositeOperation = 'destination-out'; // 使用合成模式创建月牙
ctx.beginPath();
ctx.arc(120, 80, 80, 0, Math.PI * 2); // 重叠圆
ctx.fill();
使用CSS创建月亮效果
纯CSS也可以创建一个简单的月亮形状,通过border-radius和box-shadow实现:

<div class="moon"></div>
<style>
.moon {
width: 100px;
height: 100px;
border-radius: 50%;
background: #FDB813;
position: relative;
box-shadow: 20px -20px 0 0 #FFF inset;
}
</style>
SVG实现月亮
SVG是另一种创建矢量图形的有效方式:

<svg width="200" height="200" viewBox="0 0 200 200">
<path d="M100,20 a80,80 0 1,1 0,160 a80,80 0 1,1 0,-160
M130,50 a50,50 0 1,0 0,100 z"
fill="#FDB813"/>
</svg>
动画月亮效果
为月亮添加简单的动画效果,使其看起来更生动:
function animateMoon() {
let phase = 0;
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#FDB813';
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(100 + Math.cos(phase) * 20,
100 + Math.sin(phase) * 20,
80, 0, Math.PI * 2);
ctx.fill();
phase += 0.05;
}, 50);
}
使用Three.js创建3D月亮
对于更高级的3D效果,可以使用Three.js库:
import * as THREE from 'three';
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(1, 32, 32);
const material = new THREE.MeshBasicMaterial({color: 0xFDB813});
const moon = new THREE.Mesh(geometry, material);
scene.add(moon);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
moon.rotation.x += 0.01;
moon.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();






