js实现星球转动
使用 Three.js 实现星球转动
Three.js 是一个基于 WebGL 的 JavaScript 库,用于创建 3D 图形。以下是实现星球转动的基本步骤:
-
引入 Three.js 在 HTML 文件中引入 Three.js 库:
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script> -
创建场景、相机和渲染器
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: 0x00ff00 }); const sphere = new THREE.Mesh(geometry, material); scene.add(sphere); -
设置相机位置
camera.position.z = 15; -
实现动画循环
function animate() { requestAnimationFrame(animate); sphere.rotation.y += 0.01; renderer.render(scene, camera); } animate();
使用 CSS 和 JavaScript 实现 2D 星球转动
-
HTML 结构
<div class="planet"></div> -
CSS 样式
.planet { width: 100px; height: 100px; background: radial-gradient(circle at 30% 30%, #fff, #00f); border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } -
JavaScript 动画
const planet = document.querySelector('.planet'); let angle = 0; const radius = 200; function animate() { angle += 0.01; const x = Math.cos(angle) * radius; const y = Math.sin(angle) * radius; planet.style.transform = `translate(calc(-50% + ${x}px), calc(-50% + ${y}px))`; requestAnimationFrame(animate); } animate();
使用 Canvas 实现星球转动
-
HTML 结构
<canvas id="canvas"></canvas> -
JavaScript 代码

const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let angle = 0; const radius = 100; const centerX = canvas.width / 2; const centerY = canvas.height / 2; function drawPlanet(x, y) { ctx.beginPath(); ctx.arc(x, y, 30, 0, Math.PI * 2); ctx.fillStyle = 'blue'; ctx.fill(); } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); angle += 0.01; const x = centerX + Math.cos(angle) * radius; const y = centerY + Math.sin(angle) * radius; drawPlanet(x, y); requestAnimationFrame(animate); } animate();
注意事项
- 性能优化:对于复杂的 3D 场景,建议使用 WebGL 或 Three.js 以获得更好的性能。
- 交互性:可以通过事件监听器实现用户交互,例如拖动或缩放。
- 兼容性:确保目标浏览器支持所使用的技术(如 WebGL 或 Canvas)。






