」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 � 學習 Three.js

在 � 學習 Three.js

發佈於2024-09-17
瀏覽:983

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]刪除
最新教學 更多>
  • 如何在Visual Studio 2008中設定可執行檔圖示?
    如何在Visual Studio 2008中設定可執行檔圖示?
    在Visual Studio 2008 中設定可執行檔圖示雖然提供的參考主要針對Visual Studio 2010,但在Visual Studio 中設定可執行檔圖示的原則Studio 2008 基本上都適用。但是,需要記住一些具體的注意事項:使用.ico 檔案您必須為可執行圖示使用.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 進行行動開發的能力,這個函式庫不會很快消失。然而,這樣做的問題是,大多數初學者...
    程式設計 發佈於2024-11-07
  • 使用 Tinder Unblur 個人資料
    使用 Tinder Unblur 個人資料
    Tinder 取消模糊程式碼說明 以下 JavaScript 程式碼是一個腳本,旨在對「喜歡你」部分中的 Tinder 照片進行取消模糊處理。它的工作原理是從 Tinder 的 API 獲取預告圖像並動態更新 DOM 以用清晰的圖像替換模糊的圖像。 async function ...
    程式設計 發佈於2024-11-07
  • 如何確保網站安全:最佳實踐和見解
    如何確保網站安全:最佳實踐和見解
    在當今的數位時代,確保網站的安全至關重要。隨著網路威脅變得越來越複雜,保護您的網站免受潛在漏洞的影響至關重要。以下是增強網站安全性的一些關鍵做法,以及特定網站 HouseOfParty.com 如何在其利基市場中舉例說明安全做法。 使用 HTTPS 描述:HTTPS(安全超文本傳輸協定)會對使用者...
    程式設計 發佈於2024-11-07
  • 如何使用「adjustText」函式庫解決 matplotlib 圖中註解重疊的問題?
    如何使用「adjustText」函式庫解決 matplotlib 圖中註解重疊的問題?
    Matplotlib 中的重疊註釋:綜合解決方案在資料視覺化領域,經常會遇到重疊註釋的問題,其中文字標籤彼此模糊,導致難以解釋圖表。為了應對這項挑戰,人們提出了各種方法,但對於像線重疊的複雜圖形,找到合適的解決方案可能很困難。這篇文章提出了一個使用「adjustText」函式庫的全面解決方案,提供了...
    程式設計 發佈於2024-11-07
  • 如何使用 GORM 檢索列總計?
    如何使用 GORM 檢索列總計?
    使用GORM 檢索列總計在GORM 中,透過幾個簡單的步驟即可實現從資料庫表中取得列的總和.首先,定義一個結構體來表示要檢索的資料。在這種情況下,如果您只需要工資總和,您可以建立一個帶有整數欄位的簡單結構體:type SalarySum struct { Sum float64 }接下來,使...
    程式設計 發佈於2024-11-07
  • 如何存取名稱中帶有空格的類別屬性?
    如何存取名稱中帶有空格的類別屬性?
    存取類別物件中帶有空格的屬性本問題探討如何存取名稱中包含空格的類別屬性。考慮以下範例,其中stdClass 物件具有名為「[Sector]」和「[Date Found]」的屬性:<p>stdClass Object ([Sector] =&gt; Manufacturing [D...
    程式設計 發佈於2024-11-07
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-07
  • 如何在 C++ 中正確釋放透過 Placement New 分配的記憶體?
    如何在 C++ 中正確釋放透過 Placement New 分配的記憶體?
    placement new 和delete 難題placement new 和delete 難題在C 中,當使用placement new 運算子分配記憶體時,會出現關於取消分配的適當方法的困境那個記憶。讓我們探討兩個可能的解決方案:const char* charString = "He...
    程式設計 發佈於2024-11-07
  • 單元測試:綜合指南
    單元測試:綜合指南
    单元测试是软件开发的基本实践之一,确保系统的各个单元或组件按预期运行。这些测试隔离小段代码,例如函数或方法,并验证它们在给定特定输入的情况下是否产生正确的输出。本文将深入概述单元测试、其优点、最佳实践和局限性。 什么是单元测试? 单元测试是一种软件测试技术,其中程序的各个单元(最小的可测试部分)被...
    程式設計 發佈於2024-11-07
  • 你應該盲目地用 MySQLi_ 取代 MySQL 函數:一個警世故事嗎?
    你應該盲目地用 MySQLi_ 取代 MySQL 函數:一個警世故事嗎?
    盲目地用mysqli_ 取代mysql_ 函數:一個警示故事在PHP 5.5 中,mysql_ 函數已被棄用,並已在PHP中刪除7. 這就提出了一個問題,是否可以簡單地將所有mysql_ 函數替換為mysqli_函數,而不會遇到任何不利影響。 答案是響亮的不。 功能差異雖然 mysql_ 和 mys...
    程式設計 發佈於2024-11-07
  • 了解 JavaScript 提升:簡單指南
    了解 JavaScript 提升:簡單指南
    如果您是 JavaScript 新手,您可能會遇到令人困惑的情況,即變數似乎未定義或意外彈出 ReferenceError 等錯誤。這通常可以追溯到一個稱為提升的概念。但是什麼是提升,它如何影響您的程式碼? 在本指南中,我們將詳細介紹提升的概念及其在 JavaScript 中的工作原理。最後,您將...
    程式設計 發佈於2024-11-07

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3