第一幕:创建你的第一个 Three.js 场景
现在是时候创建我们的场景并在屏幕上生成一些东西了。我们将以 Vite 项目为例,从零开始搭建一个基础的 Three.js 场景。
1. 创建 Vite 项目并安装 Three.js
首先,我们需要创建一个 Vite 项目。打开你的终端,执行以下命令:
1 2 3
| npm create vite@latest my-threejs-app -- --template vanilla cd my-threejs-app npm install
|
接下来,安装 Three.js 库:
2. 初始化场景要素
在main.js
(或你选择的入口文件)中,我们需要引入 Three.js 并设置场景的四个核心要素:场景、对象、相机和渲染器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import * as THREE from "three";
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const sizes = { width: window.innerWidth, height: window.innerHeight, };
const camera = new THREE.PerspectiveCamera( 75, sizes.width / sizes.height, 0.1, 100 );
camera.position.z = 3;
scene.add(camera);
const canvas = document.querySelector("canvas.webgl");
const renderer = new THREE.WebGLRenderer({ canvas: canvas, });
renderer.setSize(sizes.width, sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.render(scene, camera);
window.addEventListener("resize", () => { sizes.width = window.innerWidth; sizes.height = window.innerHeight;
camera.aspect = sizes.width / sizes.height; camera.updateProjectionMatrix();
renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); });
const animate = () => {
renderer.render(scene, camera);
window.requestAnimationFrame(animate); };
animate();
|
3. 更新 index.html
在你的 index.html
文件中,确保有一个 <canvas>
元素,并且引入你的 JavaScript 文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Three.js Basic Scene</title> <style> body { margin: 0; overflow: hidden; } .webgl { display: block; } </style> </head> <body> <canvas class="webgl"></canvas> <script type="module" src="/main.js"></script> </body> </html>
|
4. 运行你的应用
在终端中运行 Vite 开发服务器:
现在,你可以在浏览器中看到一个红色的立方体,这就是你创建的第一个 Three.js 场景!
总结
通过以上步骤,我们成功地创建了一个基础的 Three.js 场景,并了解了场景、对象、相机和渲染器这四个核心要素的作用。