返回

**three.js 入门:开启 WebGL 的奇妙世界**

前端

献给 three.js 初学者的入门指南:开启 WebGL 的奇妙世界

作为 JavaScript 开发人员,我们经常会遇到构建 3D 图形或可视化应用程序的需求。three.js 是一个流行且功能强大的 JavaScript 库,可让您轻松地在网络浏览器中创建和渲染 3D 图形。它建立在 WebGL 之上,WebGL 是一种流行的 JavaScript API,允许您使用图形处理单元 (GPU) 的强大功能在浏览器中创建 3D 图形。

在本文中,我们将介绍 three.js 的基本概念,并指导您创建一个简单的 3D 场景。您将学习如何使用 three.js 创建场景、添加对象、应用材质、设置灯光并控制相机。我们还将探讨一些更高级的概念,如纹理、动画和交互。

那么,让我们开始吧!

场景

场景是 three.js 中最重要的概念之一。它表示您要渲染的 3D 空间。您可以向场景中添加对象、灯光和相机。要创建一个场景,您可以使用以下代码:

const scene = new THREE.Scene();

相机

相机是您用来查看场景的虚拟相机。您可以使用以下代码创建一个透视相机:

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

渲染器

渲染器是将场景渲染到屏幕上的对象。您可以使用以下代码创建一个 WebGL 渲染器:

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

对象

对象是您添加到场景中的 3D 对象。您可以使用多种不同的形状来创建对象,例如立方体、球体、圆柱体和金字塔。要创建一个立方体,您可以使用以下代码:

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

材质

材质定义了对象的外观。您可以使用多种不同的材质,例如基本材质、phong 材质和标准材质。要创建一个基本材质,您可以使用以下代码:

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

灯光

灯光用于照亮场景中的对象。您可以使用多种不同的灯光,例如环境光、平行光和点光。要创建一个环境光,您可以使用以下代码:

const light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);

动画

您可以使用 three.js 创建动画。要创建一个简单的动画,您可以使用以下代码:

function animate() {
  requestAnimationFrame(animate);

  // Rotate the cube
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  // Render the scene
  renderer.render(scene, camera);
}

animate();

交互

您可以使用 three.js 创建交互式应用程序。要创建一个简单的交互式应用程序,您可以使用以下代码:

renderer.domElement.addEventListener('click', (event) => {
  // Get the mouse position
  const mouseX = event.clientX;
  const mouseY = event.clientY;

  // Convert mouse position to 3D world coordinates
  const vector = new THREE.Vector3();
  vector.set(mouseX, mouseY, 0.5);
  vector.unproject(camera);

  // Cast a ray from the camera to the mouse position
  const raycaster = new THREE.Raycaster();
  raycaster.setFromCamera(vector, camera);

  // Check if the ray intersects with any objects in the scene
  const intersects = raycaster.intersectObjects(scene.children);

  // If the ray intersects with an object, change its color
  if (intersects.length > 0) {
    intersects[0].object.material.color.set(0xff0000);
  }
});

结语

three.js 是一个功能强大且易于使用的库,可用于创建 3D 图形。在本文中,我们介绍了 three.js 的基本概念,并指导您创建了一个简单的 3D 场景。您现在可以开始使用 three.js 构建自己的 3D 应用程序了!