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

在 � 中学习 Three.js

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

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]删除
最新教程 更多>
  • 你真的了解Git吗?
    你真的了解Git吗?
    本博客中的图片来自 Scott Chacon、Ben Straub 的“Pro Git” 在本博客中,您将了解有关您在编程中使用的 Git 中的一些日常功能的各种精彩事实! 开发人员很容易盲目使用工具而不知道它们在幕后是如何工作的。虽然这种抽象是为了更好,但了解事物如何工作有时可能是经验丰富的程...
    编程 发布于2024-11-07
  • 浓缩咖啡;出发时间到了
    浓缩咖啡;出发时间到了
    过去的两周里,我用 Go 重写了我的基于 Rust 的 Java 构建工具,事情进展得更快。 Espresso 运行速度更快且更便携。 Espresso 最近还能够编译和打包它的第一个项目,即我的另一个项目 Kindling。 我希望能得到有关 Espresso 的任何反馈。有很多功能缺失,例如瞬态...
    编程 发布于2024-11-07
  • 为什么我的 JSFiddle 无法运行?
    为什么我的 JSFiddle 无法运行?
    调试无功能的 JSFiddle尝试在 JSFiddle 中运行简约代码片段时,用户可能会遇到意外的功能缺失。此问题通常是由于 JavaScript 设置中的疏忽而引起的。要解决此问题,请按照下列步骤操作:在 JavaScript 设置中找到“加载类型”下拉列表。选择“无换行 - 底部”。此设置可确...
    编程 发布于2024-11-07
  • GenAI Git 提交
    GenAI Git 提交
    生成 git 提交消息很快成为开发人员的经典 GenAI 应用程序。 为了解决这个问题,我们将制作一个 GenAIScript 脚本。 该脚本充当常规 Node.js 自动化脚本并使用 runPrompt 向 LLM 发出呼叫并要求用户确认生成的文本。 ? 解释脚本 脚本首先从 @...
    编程 发布于2024-11-07
  • 什么是 Webhook 以及如何有效使用它们
    什么是 Webhook 以及如何有效使用它们
    Webhooks 是集成不同系统并实时发送通知的强大工具。它们允许一个应用程序在事件发生时自动通知另一个应用程序,而无需像传统 API 那样不断发出请求来检查是否有新内容。在这篇文章中,我们将了解它们的工作原理、如何配置它们,并且我们将探索使用 Webhook.site 工具的实际示例,该工具有助...
    编程 发布于2024-11-07
  • 创建 JS 函数以删除给定字符串中的空格。 (使用核心js而不是内置的修剪功能。)
    创建 JS 函数以删除给定字符串中的空格。 (使用核心js而不是内置的修剪功能。)
    const trim = (string) => { let strArr = string.split(""); let trimedStr = []; strArr.forEach((item) => { if (item !== " ") { ...
    编程 发布于2024-11-07
  • GlobalErrorHandler:捕获从 ErrorBoundary 手中落下的错误!
    GlobalErrorHandler:捕获从 ErrorBoundary 手中落下的错误!
    ErrorBoundary 是一个出色的工具,可以捕获 React 组件抛出的错误。您可以根据错误本身的性质和位置提供自定义错误消息。但并非所有抛出的错误都由 ErrorBoundary 处理!你用这些做什么? 当考虑异步错误和从 React 外部抛出的错误时,ErrorBoundary 不够。为了...
    编程 发布于2024-11-07
  • 如何在Visual Studio 2008中设置可执行文件图标?
    如何在Visual Studio 2008中设置可执行文件图标?
    在 Visual Studio 2008 中设置可执行文件图标虽然提供的参考主要针对 Visual Studio 2010,但在 Visual Studio 中设置可执行文件图标的原则Studio 2008 基本上都适用。但是,需要记住一些具体的注意事项:使用 .ico 文件您必须为可执行图标使用 ...
    编程 发布于2024-11-07
  • 导入大型 SQL 文件:为什么使用 MySQL 控制台而不是 phpMyAdmin?
    导入大型 SQL 文件:为什么使用 MySQL 控制台而不是 phpMyAdmin?
    在 phpMyAdmin 中导入大型 SQL 文件:另一种方法尝试直接通过 phpMyAdmin 导入大量 SQL 文件可能会遇到限制。不过,有一个可靠的替代方法,即利用 MySQL 控制台。根据提供的建议,通过 MySQL 控制台导入 SQL 文件可以绕过 phpMyAdmin 中遇到的问题。此方...
    编程 发布于2024-11-07
  • 使用 JSON-LD 提升博客的 SEO:我如何使用结构化数据添加丰富的结果
    使用 JSON-LD 提升博客的 SEO:我如何使用结构化数据添加丰富的结果
    Introduction A few years ago in 2022, I attended SCaLE 19x. For those who are not aware, SCaLE is an acronym which stands for Southern Califo...
    编程 发布于2024-11-07
  • create-next-app 使用此包验证您的应用程序名称
    create-next-app 使用此包验证您的应用程序名称
    在本文中,我们分析 create-next-app 如何验证您的项目名称。 validate: (name) => { const validation = validateNpmName(basename(resolve(name))) if (validation.valid) { ...
    编程 发布于2024-11-07
  • 幕后反应:到底发生了什么?
    幕后反应:到底发生了什么?
    React 长期以来一直是首选的 JavaScript 库,并且很容易成为世界上最受欢迎的库之一。此外,随着 Next.js 和 Remix 等流行框架构建在 React 之上,以及使用 React-Native 进行移动开发的能力,这个库不会很快消失。然而,这样做的问题是,大多数初学者都涌向 Re...
    编程 发布于2024-11-07
  • 使用 Tinder Unblur 个人资料
    使用 Tinder Unblur 个人资料
    Tinder 取消模糊代码说明 以下 JavaScript 代码是一个脚本,旨在对“喜欢你”部分中的 Tinder 照片进行取消模糊处理。它的工作原理是从 Tinder 的 API 获取预告图像并动态更新 DOM 以用清晰的图像替换模糊的图像。 async function unb...
    编程 发布于2024-11-07
  • 如何确保网站安全:最佳实践和见解
    如何确保网站安全:最佳实践和见解
    在当今的数字时代,确保网站的安全至关重要。随着网络威胁变得越来越复杂,保护您的网站免受潜在漏洞的影响至关重要。以下是增强网站安全性的一些关键做法,以及特定网站 HouseOfParty.com 如何在其利基市场中举例说明安全做法。 使用 HTTPS 描述:HTTPS(安全超文本传输​​协议)对用户和...
    编程 发布于2024-11-07
  • 如何使用“adjustText”库解决 matplotlib 图中注释重叠的问题?
    如何使用“adjustText”库解决 matplotlib 图中注释重叠的问题?
    Matplotlib 中的重叠注释:综合解决方案在数据可视化领域,经常会遇到重叠注释的问题,其中文本标签彼此模糊,导致难以解释图表。为了应对这一挑战,人们提出了各种方法,但对于像线重叠的复杂图形,找到合适的解决方案可能很困难。这篇文章提出了一个使用“adjustText”库的全面解决方案,提供了比传...
    编程 发布于2024-11-07

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

Copyright© 2022 湘ICP备2022001581号-3