以下是一个使用 JavaScript 和 Three.js 库实现 3D 滚动球体的简单动画代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D 滚动球体</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// 创建场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
// 创建渲染器
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);
// 动画函数
function animate() {
requestAnimationFrame(animate);
// 使球体沿 x 轴滚动
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
// 监听窗口大小变化,调整渲染器尺寸
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
基础概念:
优势:
类型:
应用场景:
常见问题及解决方法:
希望这个示例对你有帮助!如果你还有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云