js实现球状
使用Three.js创建3D球体
Three.js是一个流行的JavaScript 3D库,适合快速创建球体等3D对象。
安装Three.js
通过npm或CDN引入:
npm install three
或HTML中直接引入:
<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(1, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.z = 5;
// 动画循环
function animate() {
requestAnimationFrame(animate);
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
使用Canvas 2D绘制球状效果
通过Canvas的径向渐变模拟3D球体视觉效果。
代码示例
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 创建径向渐变
const gradient = ctx.createRadialGradient(200, 200, 0, 200, 200, 100);
gradient.addColorStop(0, 'white');
gradient.addColorStop(1, 'blue');
// 绘制球体
ctx.beginPath();
ctx.arc(200, 200, 100, 0, Math.PI * 2);
ctx.fillStyle = gradient;
ctx.fill();
ctx.stroke();
</script>
使用CSS 3D变换
通过CSS的border-radius和box-shadow实现球状效果。
代码示例
<div class="sphere"></div>
<style>
.sphere {
width: 200px;
height: 200px;
border-radius: 50%;
background: radial-gradient(circle at 30% 30%, #fff, #00f);
box-shadow: inset -10px -10px 20px rgba(0, 0, 0, 0.5);
}
</style>
使用WebGL原生API
直接调用WebGL API实现球体渲染,适合需要高性能定制的场景。
代码示例
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点和片段着色器代码
const shaderSource = `
attribute vec3 aPosition;
void main() {
gl_Position = vec4(aPosition, 1.0);
}
`;
// 初始化着色器、缓冲区等
// (此处省略详细WebGL初始化步骤,需包含顶点数据和渲染逻辑)
性能优化建议
- Three.js:使用
SphereBufferGeometry替代SphereGeometry以减少内存占用。 - Canvas:减少重绘频率,使用
requestAnimationFrame优化动画。 - CSS:避免过多阴影叠加,影响渲染性能。
根据需求选择合适的方法:Three.js适合复杂3D场景,Canvas/CSS适合轻量级实现,WebGL适合底层控制。







