”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 � 中学习 Three.js

在 � 中学习 Three.js

发布于2024-09-17
浏览:393

I had the chance to dive into some web development where I wanted to add interactive 3D elements that could move and react to certain triggers. Naturally, this led me to explore Three.js — a super popular library for rendering 3D graphics on the web.

While learning Three.js, I went through a ton of blogs, tutorials, and resources, and I thought, “Why not summarize my journey and share a really cool example?” So, if you’re someone who wants to get started with Three.js, I’ve put together this guide just for you.

As we step into 2024, the need for immersive and interactive 3D experiences is skyrocketing. Whether it’s for e-commerce sites showing 3D models of products, educational platforms using 3D simulations, or even games — 3D technology is transforming the way we engage with digital content. And the best part? With Three.js, creating these experiences is easier than ever!

In this guide, I’ll take you step-by-step through Three.js, and by the end, you’ll have built a 3D scene with a floating astronaut in space. ?‍??

Ready to dive in? Let’s get started!

Why Learn Three.js in 2024? ?

Three.js provides a simple yet powerful way to bring these 3D experiences to the web. Here’s why learning Three.js is a fantastic idea in 2024:

  1. WebXR and WebGL: Virtual reality (VR) and augmented reality (AR) on the web are growing, and Three.js is WebXR-ready.
  2. Cross-Browser Support: It works seamlessly across modern browsers, including mobile ones.
  3. Lightweight 3D Creation: No need to learn complex WebGL. Three.js makes 3D creation as easy as writing JavaScript.
  4. Growing Community: With more than a decade of active development, the library has an ever-growing collection of plugins and examples.

Setting Up: Your First Three.js Scene

Let’s start with the basics. The magic of Three.js starts with three core concepts: Scene, Camera, and Renderer. If you understand these, you’re already halfway there!

1. The Scene ?️

Think of the scene as your 3D canvas. It contains all the objects, lights, and cameras needed to create the final 3D rendering.

const scene = new THREE.Scene();

2. The Camera ?

The camera is your “viewpoint” into the 3D world. In 2024, most developers use PerspectiveCamera, which simulates how human eyes see the world.

const camera = new THREE.PerspectiveCamera(
  75, // Field of view
  window.innerWidth / window.innerHeight, // Aspect ratio
  0.1, // Near clipping plane
  1000 // Far clipping plane
);
camera.position.z = 5; // Move the camera back so we can see the objects

3. The Renderer ?

The renderer converts the 3D scene and camera into a 2D image for the browser to display. In 2024, we typically use WebGLRenderer, which is optimized for modern browsers.

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement); 
// Adds the canvas to the webpage

4. Creating a Simple 3D Object: A Cube ?

Let’s create our first 3D object: a cube. We define its geometry, give it a material, and combine them into a mesh.

const geometry = new THREE.BoxGeometry(); // Define the shape (cube)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
 // Apply a green color to the cube
const cube = new THREE.Mesh(geometry, material); 
// Combine the geometry and material into a 3D mesh
scene.add(cube); // Add the cube to the scene

5. Animating the Cube ?

3D is all about movement! Let’s make our cube rotate. To do this, we create an animation loop using requestAnimationFrame, which ensures smooth 60fps rendering.

function animate() {
  requestAnimationFrame(animate); // Keep looping the function for continuous animation

  cube.rotation.x  = 0.01; // Rotate cube on the X axis
  cube.rotation.y  = 0.01; // Rotate cube on the Y axis
renderer.render(scene, camera); // Render the scene from the camera's perspective
}
animate(); // Start the animation loop

Putting It All Together:

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

Congrats! ? You’ve now set up the basics of a 3D world ! ?

Adding Objects to the Scene ?️

Now that we have a scene, camera, and renderer, it’s time to add some 3D objects! We’ll start with something simple: a rotating cube.

const geometry = new THREE.BoxGeometry(); // Defines the shape
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); 
// Adds color to the shape
const cube = new THREE.Mesh(geometry, material); 
// Combines the shape and color
scene.add(cube); // Adds the cube to the scene

Adding Animation:

Now let’s animate the cube so it spins! Real-time graphics need smooth animations, and we can achieve that with requestAnimationFrame.

function animate() {
  requestAnimationFrame(animate); // Keep looping through this function

  cube.rotation.x  = 0.01; // Rotate the cube around the X axis
  cube.rotation.y  = 0.01; // Rotate the cube around the Y axis

renderer.render(scene, camera); // Render the scene from the perspective of the camera

}
animate(); // Start the animation loop

And boom ? — You’ve just created your first animated 3D object in Three.js!

Taking It Up a Notch

Lights, Materials, and Shadows ?

3D graphics are nothing without light. The more realistic the lighting, the more impressive your 3D world becomes. Let’s explore:

Adding Lights ?

Without light, even the best 3D models will look flat and lifeless. In Three.js, there are several types of lights:

  • AmbientLight: Provides soft global lighting that illuminates all objects equally.
  • DirectionalLight: Simulates sunlight, casting parallel light rays in a specific direction.
const ambientLight = new THREE.AmbientLight(0x404040, 2);
 // Soft light to brighten the scene
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1).normalize(); 
// Light from top-right corner
scene.add(directionalLight);

Better Materials for Realism ?

MeshStandardMaterial is the go-to material for creating objects that look realistic.

const material = new THREE.MeshStandardMaterial({ color: 0xff0051, metalness: 0.6, roughness: 0.4 });

Interactivity with OrbitControls ?️

What’s a 3D scene without interactivity? With OrbitControls, you can let users rotate, pan, and zoom in your 3D world.

const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update(); // Make sure the controls stay in sync with the camera

Textures and Models: Bringing Realism to Life ?

loading 3D models and textures is key to building immersive experiences. Here’s how to load a 3D model of, say, a floating astronaut (because why not? ?):

Using the GLTFLoader:

const loader = new THREE.GLTFLoader();
loader.load('/path-to-your-model/astronaut.glb', function (gltf) {
  scene.add(gltf.scene); // Add the astronaut to the scene
});

Real-World Example: Floating Astronaut in Space ??‍?

Let’s bring everything together with a complete example — a floating astronaut in space! This example demonstrates everything we’ve covered so far: 3D models, textures, lights, animations, and interactivity.

Learning Three.js in �

Key Aspects of the Code:

Astronaut Model:

The astronaut model (astronaut.glb) is loaded using useGLTF().
The model uses several textures (color, roughness, metalness, normal, and ambient occlusion).

Textures:

  1. Color Texture: Adds base color to the astronaut model.
  2. Roughness Texture: Determines how rough or smooth the surface of the astronaut is.
  3. Metalness Texture: Controls how metallic the material looks.
  4. Normal Texture: Adds surface detail to make the astronaut’s surface look more realistic.
  5. Ambient Occlusion (AO): Adds shadows in crevices to give the astronaut model more depth.

Lighting:

  1. Ambient Light: Adds overall brightness to the scene.
  2. Directional Light: Illuminates the astronaut from one direction, simulating sunlight.
  3. Spot Light: Adds focused light on the astronaut to emphasize key areas.

Post-Processing:

Bloom: A bloom effect is used to create a subtle glow, enhancing the overall visual appeal.

Controls:

OrbitControls: Allows the user to interact with the scene by zooming and panning around the astronaut.

Final Code for Floating Astronaut:

The code you provided implements a 3D floating astronaut in space using Three.js, React Three Fiber, and various textures. Below is an explanation of the code along with some minor improvements:

import * as THREE from 'three';
import React, { useRef, useEffect } from 'react';
import { Canvas, useFrame, useLoader } from '@react-three/fiber';
import { OrbitControls, useGLTF } from '@react-three/drei';
import { TextureLoader, AnimationMixer, BackSide } from 'three';
import { EffectComposer, Bloom } from '@react-three/postprocessing';

const Astronaut = () => {
  const { scene, animations } = useGLTF('/astronaut.glb'); // Load the astronaut model
  const mixer = useRef(null);

  useEffect(() => {
    scene.scale.set(0.3, 0.3, 0.3); // Scale down the astronaut
  }, [scene]);

  useFrame((state, delta) => {
    if (!mixer.current && animations.length) {
      mixer.current = new AnimationMixer(scene);
      mixer.current.clipAction(animations[0]).play();
    }
    if (mixer.current) mixer.current.update(delta);
  });

  return ;
};

const SpaceBackground = () => {
  const texture = useLoader(TextureLoader, '/textures/space-background.jpg');
  return (
    
  );
};

const App = () => {
  return (
    
  );
};

export default App;
  • Astronaut Model: The astronaut model is loaded using GLTFLoader, animated with AnimationMixer.
  • Space Background: A large textured sphere acts as the space backdrop.
  • Lighting: Ambient and directional lights make the astronaut stand out, while bloom adds a glowing effect.
  • Interactivity: Users can pan, zoom, and rotate using OrbitControls. Heres how the result looks like:

Learning Three.js in �

Wrapping Up ?

With Three.js, creating stunning 3D experiences has never been easier. Whether you’re interested in building games, interactive websites, or visualizing data in 3D, the possibilities are endless. In 2024, the web is more immersive than ever, and with Three.js, you can be a part of this exciting future.

GitHub Repository ?

You can find the full source code for the floating astronaut in space project on GitHub. Feel free to explore, clone, and modify it to suit your needs.

GitHub Repository: 3D Floating Astronaut Project

Assets and Image Links ?

  • 3D Astronaut Model: The astronaut model used in this project can be found on Sketchfab.
    Animated Floating Astronaut in Space Suit (Sketchfab)

  • Background Image: The background space image is provided by Alex Myers from Pixabay.
    Image by Alex Myers from Pixabay.

Happy coding, future 3D creator! ?

版本声明 本文转载于:https://dev.to/ankitakanchan/learning-threejs-in-2024-40id?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 感到没有动力
    感到没有动力
    感觉自己像个菜鸟,放弃了几次。 我第一次开始考虑编码是在我还是个孩子的时候,但我选择成为一名社交蝴蝶,现在我已经 26 岁了,尝试了很多次学习编码 python、JS、React、DB 等但最终,我感到不知所措并放弃了它。 现在,正因为如此,我感觉自己像个失败的松手,我想解决这个...
    编程 发布于2024-11-07
  • 如何使用 VS Code 调试 Go 单元测试中冲突的 Protobuf 扩展?
    如何使用 VS Code 调试 Go 单元测试中冲突的 Protobuf 扩展?
    使用标志运行和调试单元测试:解决 Protobuf 扩展冲突在 VS Code 中调试单元测试时,可能需要通过用于解决 Protobuf 扩展冲突的附加标志。本指南提供了此问题的解决方案,允许无缝调试。VS Code settings.json 中的原始配置尝试添加所需的标志 '-ldfla...
    编程 发布于2024-11-07
  • string-width-cjs npm 包的神秘供应链问题
    string-width-cjs npm 包的神秘供应链问题
    这个故事始于 Docusaurus(基于 React 的开源文档项目)的维护者 Sébastien Lorber 注意到对包清单的 Pull 请求更改。以下是对流行的 cliui npm 包提出的更改: 具体来说,让我们注意使用不熟悉的语法的 npm 依赖项更改: "dependencies":...
    编程 发布于2024-11-07
  • 使用 Playwright-Network-Cache 增强您的 ETests
    使用 Playwright-Network-Cache 增强您的 ETests
    简介 当使用像 Playwright 这样的端到端测试框架时,处理网络请求通常是一项复杂的任务。依赖外部 API 的测试可能会很慢且不一致,从而引入不必要的不​​稳定。由于服务器缓慢或不可靠,在一次测试运行中成功的网络调用可能在下一次测试运行中失败,从而导致结果不一致。为了解决这个...
    编程 发布于2024-11-07
  • Django Stack 入门:创建完整项目
    Django Stack 入门:创建完整项目
    如果您是 Python 世界的新手,并且想知道 Django 到底是什么,这里有一篇文章可能会有所帮助,作为实用的介绍。 Django 就像您希望一直拥有的工具包。它使得构建强大的、可扩展的 Web 应用程序不仅成为可能,而且真正变得有趣。你猜怎么着?您无需成为专家即可开始。 在本指南中,我们将采...
    编程 发布于2024-11-07
  • 掌握“项目:使用 Vue.js 实现主页数据的动态化”
    掌握“项目:使用 Vue.js 实现主页数据的动态化”
    您是否希望提高您的网络开发技能并创建动态的、具有视觉吸引力的主页? LabEx 提供的项目:主页数据动态化课程就是您的最佳选择。 在这个基于项目的综合学习体验中,您将深入了解 Vue.js 的世界,这是一个强大的 JavaScript 框架,使开发人员能够构建迷人的用户界面。通过分步方法,您将学习如...
    编程 发布于2024-11-07
  • 如何将参数传递给使用“chrome.tabs.executeScript()”注入的内容脚本?
    如何将参数传递给使用“chrome.tabs.executeScript()”注入的内容脚本?
    将参数传递给使用 chrome.tabs.executeScript() 注入的内容脚本使用 chrome.tabs.executeScript 注入内容脚本文件时({file: "content.js"}),出现一个常见问题:如何在内容脚本文件中向 JavaScript 传递参...
    编程 发布于2024-11-07
  • 自定义 Django 面板:分步指南
    自定义 Django 面板:分步指南
    在本指南中,我将引导您了解如何修改和扩展 Django 默认管理面板/界面,使其更加用户友好。 1.设置项目: 首先在 Django 中创建一个全新的项目和应用程序 django-admin startproject myprojectname cd myprojectname python man...
    编程 发布于2024-11-07
  • 了解身份验证流程
    了解身份验证流程
    什么是身份验证流程? 身份验证流程是确认用户身份并管理他们对应用程序某些部分的访问的过程。当您使用网络应用程序(例如社交媒体网站)时,这涉及检查用户是否是他们所说的人(登录),然后授予他们访问某些功能的权限。 它在 React 中是如何工作的? 在 React 中,...
    编程 发布于2024-11-07
  • 如何使用 mysqli_pconnect() 在 PHP 中实现 MySQL 连接池?
    如何使用 mysqli_pconnect() 在 PHP 中实现 MySQL 连接池?
    MySQL 的 PHP 连接池在 PHP 中,维护数据库连接会影响性能。为了优化这一点,开发人员经常考虑使用连接池技术。MySQL 的连接池MySQL 没有内置的连接池机制。然而,MySQLi 扩展提供了 mysqli_pconnect() 函数,其作用与 mysqli_connect() 类似,但...
    编程 发布于2024-11-07
  • 将 HTMX 添加到 GO
    将 HTMX 添加到 GO
    HTMX 是 intercooler.js 的后继者,用于使用 HTTP 命令扩展 HTML,而无需编写 API。现在,我知道一开始我说我要删除抽象层,但是我更多的是系统/工具程序员,所以我仍然需要一些抽象,直到我掌握了底层实际发生的情况。 基本概念 HTMX 部署 AJAX 命令来...
    编程 发布于2024-11-07
  • 发现 itertools
    发现 itertools
    Itertools 是最有趣的 Python 库之一。它包含一系列受函数式语言启发的函数,用于与迭代器一起使用。 在这篇文章中,我将提到一些最引起我注意并且值得牢记的内容,以免每次都重新发明轮子。 数数 好几次我都实现了无限计数(好吧,结束了 显式地在某个点用中断)使用 while ...
    编程 发布于2024-11-07
  • 为什么每个人都应该学习 Go(即使您认为生活中不需要另一种语言)
    为什么每个人都应该学习 Go(即使您认为生活中不需要另一种语言)
    啊,Go,编程语言。您可能听说过,也许是从办公室里一位过于热情的开发人员那里听说过的,他总是不停地谈论他们的 API 现在有多“快得惊人”。当然,您已经涉足过其他语言,也许您会想:“我真的需要另一种语言吗?”剧透警报:是的,是的,你知道。 Go 就是那种语言。让我以最讽刺、最真诚的方式为你解释一下。...
    编程 发布于2024-11-07
  • 如何计算 Pandas 中多列的最大值?
    如何计算 Pandas 中多列的最大值?
    在 Pandas 中查找多列的最大值假设您有一个包含多列的数据框,并且希望创建一个包含两个或多个列中的最大值的新列现有的列。例如,给定 A 列和 B 列,您需要创建 C 列,其中:C = max(A, B)要完成此任务:使用 max 函数和 axis=1 计算指定列中每行的最大值:df[["...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3