首页 > 科技 >

✨ three.js 入门案例 ✨

发布时间:2025-03-23 11:20:51来源:

对于想探索3D世界的开发者来说,three.js 是一个绝佳的选择!它基于WebGL,让复杂的3D渲染变得简单易懂。今天就来分享一个基础入门案例,带你快速上手!

首先,确保你的项目引入了three.js库,可以通过CDN轻松加载:

```html

<script src="https://cdn.jsdelivr.net/npm/three@0.152.4/build/three.min.js"></script>

```

接下来,创建一个基本场景:

```javascript

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.BoxGeometry();

const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

const cube = new THREE.Mesh(geometry, material);

scene.add(cube);

function animate() {

requestAnimationFrame(animate);

cube.rotation.x += 0.01;

cube.rotation.y += 0.01;

renderer.render(scene, camera);

}

animate();

```

运行代码后,你会看到一个旋转的绿色立方体!🎉

通过这个简单的例子,你已经掌握了three.js的核心概念:场景、摄像机和渲染器。继续尝试更多材质、灯光以及模型加载吧!💡

免责声明:本答案或内容为用户上传,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。 如遇侵权请及时联系本站删除。