3D 技术已经不再是游戏引擎的专属,随着浏览器技术的发展,我们完全可以在网页上实现令人惊艳的 3D 效果。而 Three.js,作为 WebGL 的封装库,让 Web 3D 的大门向更多开发者敞开了。
这是我开启这个 Three.js 专栏的第一篇文章,我们将简单认识一下 Three.js,并为后续的项目开发打下基础。
Three.js 是一个 JavaScript 3D 库,它封装了 WebGL,使开发者可以用更简单的方式在浏览器中创建和展示 3D 内容。
通过 Three.js,你可以轻松实现以下效果:
适合以下人群:
以下是 Three.js 常见的使用场景:
名称 | 简介 | 链接 |
---|---|---|
官网 | Three.js 官方网站 | https://threejs.org |
文档 | 官方 API 文档 | https://threejs.org/docs/ |
示例 | 各种 Three.js 示例 | https://threejs.org/examples/ |
GitHub | 项目源码仓库 | https://github.com/mrdoob/three.js |
React Three Fiber | React 开发者专用封装 | https://docs.pmnd.rs/react-three-fiber |
模型/纹理下载 | 免费素材库 | https://sketchfab.com, https://poly.pizza, https://readyplayer.me/ |
Three.js中文网 | 其他博主网站 | http://www.webgl3d.cn/pages/4a14ce/ |
先放一个最简单的示例:创建一个旋转的立方体 ,你可以在菜鸟教程运行下面示例:在线运行html
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Three.js!title>
<style>body { margin: 0; }style>
head>
<body>
<script src="https://unpkg.com/[email protected]/build/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.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();
script>
body>
html>
接下来我们将手把手写一个更完整的场景,讲解:
如何添加多个物体
如何设置光源与阴影
如何实现用户交互(如鼠标旋转控制)
后续我们还会结合 React 使用 react-three-fiber 构建一个炫酷的个人主页项目 ️✨