Three.js 快速指南



Three.js - 簡介

所有現代瀏覽器都變得更加強大,並且可以直接使用 JavaScript 訪問。它們採用了 WebGL(Web 圖形庫),這是一個 JavaScript API,允許你使用 GPU(圖形處理單元)的功能,在任何相容的 Web 瀏覽器中渲染高效能的互動式 3D 和 2D 圖形。

但是 WebGL 是一個非常底層的系統,它只繪製點、正方形和線等基本物件。然而,直接從 JavaScript 程式設計 WebGL 是一個非常複雜和冗長的過程。你需要了解 WebGL 的內部細節並學習複雜的著色器語言才能充分利用 WebGL。這時,**Three.js** 就派上用場了,它可以簡化你的工作。

什麼是 Three.js?

Three.js 是一個開源的、輕量級的、跨瀏覽器的、通用的 JavaScript 庫。Three.js 在幕後使用 WebGL,因此你可以用它在瀏覽器中的 HTML <canvas> 元素上渲染圖形。由於 Three.js 使用 JavaScript,你可以與其他網頁元素互動,新增動畫和互動,甚至建立一個包含一些邏輯的遊戲。

為什麼要使用 Three.js?

以下特性使 Three.js 成為一個優秀的庫:

  • 你只需要使用 JavaScript 就可以建立複雜的 3D 圖形。

  • 你可以在瀏覽器內建立虛擬現實 (VR) 和增強現實 (AR) 場景。

  • 因為它使用 WebGL,所以它具有跨瀏覽器支援。許多瀏覽器都支援它。

  • 你可以新增各種材質、紋理併為 3D 物件新增動畫。

  • 你還可以載入和處理來自其他 3D 建模軟體的物件。

只需幾行 JavaScript 程式碼和簡單的邏輯,你就可以建立任何東西,從高效能互動式 3D 模型到逼真的即時場景。

以下是一些使用 Three.js 建立的優秀網站:

你可以在 three.js 的官方網站上找到更多示例

瀏覽器支援

目前,桌上型電腦和移動裝置上的所有現代瀏覽器都支援 WebGL。唯一需要注意的瀏覽器是移動版 Opera Mini 瀏覽器。對於 IE 10 及更舊版本,可以使用 IEWebGL 外掛,你可以從 https://github.com/iewebgl/iewebgl./ 獲取。你可以在這裡 找到有關 WebGL 瀏覽器支援的詳細資訊。

一旦你理解了 Three.js 是什麼,就可以繼續學習下一章,瞭解如何設定專案以開始使用 Three.js。

Three.js - 安裝

有多種方法可以將 Three.js 包含到你的專案中。你可以使用以下任何方法開始使用 Three.js。然後開啟你喜歡的程式碼編輯器開始工作。

下載完整的 Three.js 專案

將完整的 Three.js 專案下載到你的系統中。你可以從 這裡GitHub 下載。解壓 three.js-master.zip 檔案,檢視 build 資料夾內的內容。你會找到兩個檔案:three.js 和 three.min.js(只是一個精簡版本)。將這兩個檔案中的任何一個新增到你的專案資料夾中,並將其連結到你的 HTML 檔案。現在你就可以在你的專案中使用 Three.js 了。

**注意** - 我們建議使用精簡版本,因為它載入速度更快。

將以下 <script> 標籤插入到 HTML 的 <head> 元素中,其中包含 threejs.min.js 檔案的路徑。

<script src='/path/to/threejs.min.js'></script>

使用 CDN 連結

你可以從 CDN(內容分發網路)連結檔案,CDN 是一個專門用於託管檔案的遠端站點,以便你可以線上使用它們。你可以使用以下任何網站:

將以下任何 <script> 標籤插入到 HTML 的 <head> 元素中。

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>

或者

<script src="https://cdn.jsdelivr.net/npm/three@0.127.0/build/three.min.js"></script>

安裝 Three.js 的包

Three.js 也可以作為 NPM 上的包。如果你在你的計算機上安裝了 Node.js,你可以使用 npm 或 yarn 來安裝它。

npm install three

或者

yarn add three

然後,你可以將 Three.js 從 three.module.js 檔案匯入到你的 JavaScript 檔案中

import * as THREE from 'three'

你可以將 Three.js 與任何 JavaScript 框架(如 React、Angular、Vue)一起使用。

專案設定完成後,讓我們開始建立。

Three.js - Hello Cube 應用

像任何其他程式語言一樣,讓我們透過建立“Hello cube!”應用來學習 Three.js。

HTML 程式碼

<!DOCTYPE html>
<html>
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <meta charset="UTF-8" />
      <title>Three.js - Hello cube</title>
      <style>
         /* Our CSS goes here */
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>
   </head>
   <body>
      <div id="threejs-container">
         <!-- Our output to be rendered here →
      </div>
      <script type="module">
         // our JavaScript code goes here
      </script>
   </body>
</html>

如你所見,它只是一個包含 Three.js CDN 的簡單 HTML 檔案。

CSS 程式碼

<style>
* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
   font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
   Oxygen,
   Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
html,
body {
   height: 100vh;
   width: 100vw;
}
#threejs-container{
   position: block;
   width: 100%;
   height: 100%;
}
</style>

上面的 CSS 程式碼只是 HTML 頁面的基本樣式。threejs-container 佔據整個螢幕。

JavaScript 程式碼

這就是我們的 three.js 應用的實現之處。下面的程式碼在螢幕中央渲染一個立方體。所有這些程式碼都將進入 HTML 中的空 <script> 標籤。

const width = window.innerWidth
const height = window.innerHeight
// Scene
const scene = new THREE.Scene()
scene.background = new THREE.Color('#00b140')
// Camera
const fov = 45 // AKA Field of View
const aspect = window.innerWidth / window.innerHeight
const near = 0.1 // the near clipping plane
const far = 100 // the far clipping plane
const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)
// Renderer
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
// Creating a cube
const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({ wireframe: true })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// Rendering the scene
const container = document.querySelector('#threejs-container')
container.append(renderer.domElement)
renderer.render(scene, camera)

讓我們一步一步地討論程式碼,然後你可以在接下來的章節中獲得有關每個元素的更多資訊。首先,我們需要建立一個場景、一個相機和一個渲染器。這些是構成每個 Three.js 應用的基本元件。

場景

const scene = new THREE.Scene()
scene.background = new THREE.Color('#262626')

場景作為我們可以在螢幕上看到的所有內容的容器,如果沒有 THREE.Scene 物件,Three.js 就無法渲染任何內容。背景顏色為深灰色,以便我們看到立方體。

相機

const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)

相機物件定義了我們渲染場景時將看到的內容。相機型別不多,但對於此示例,我們將使用 PerspectiveCamera,它與我們眼睛觀察世界的方式相匹配。

渲染器

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

渲染器物件負責根據相機計算場景在瀏覽器中的外觀。有多種型別的渲染器,但我們主要使用 WebGLRenderer,因為大多數瀏覽器都支援 WebGL。

除了建立渲染器例項之外,我們還需要設定我們希望它渲染應用的大小。最好使用我們想要用應用填充的區域的寬度和高度——在本例中,是瀏覽器視窗的寬度和高度。

立方體

const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({
   color: 0xffffff,
   wireframe: true,
})
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

上面的程式碼在螢幕中央建立一個簡單的立方體。我們可以使用 THREE.Mesh 建立任何物件。Mesh 接受兩個物件:幾何體和材質。網格的幾何體定義其形狀,材質確定物件的表面屬性。

要建立一個立方體,我們需要 BoxGeometry 和一個主要材質 (MeshBasicMaterial),顏色為 0xffffff。如果將 wireframe 屬性設定為 true,則它會告訴 Three.js 顯示線框而不是實體物件。

渲染場景

const container = document.querySelector('#threejs-container')
container.append(renderer.domElement)
renderer.render(scene, camera)

示例

最後但並非最不重要的是,我們將渲染器元素新增到我們的 HTML 文件中。渲染器使用 <canvas> 元素向我們顯示場景。在本例中,渲染器將 <canvas> 元素附加到 HTML 中的參考容器。

hello-cube-app.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js – Hello cube</title>
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
            Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
         }
         html,
         body {
            height: 100vh;
            overflow: hidden;
            width: 100vw;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
   </head>
   <body>
      <div id="threejs-container"></div>
      <script type="module">
         // Hello Cube App
         // Your first Three.js application
         // sizes
         const width = window.innerWidth
         const height = window.innerHeight
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
         camera.position.set(0, 0, 10)
         // cube
         const geometry = new THREE.BoxGeometry(2, 2, 2)
         const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
         })
         const cube = new THREE.Mesh(geometry, material)
         scene.add(cube)
         // renderer
         const renderer = new THREE.WebGL1Renderer()
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // rendering the scene
         const container = document.querySelector('#threejs-container')
         container.append(renderer.domElement)
         renderer.render(scene, camera)
      </script>
   </body>
</html>

輸出

如果一切正常,輸出如下所示。嘗試修改程式碼以更好地理解其工作原理。

你現在已經完成了你的第一個 three.js 應用程式的建立。讓我們繼續為該應用新增更多美感。

Three.js - 渲染器與響應式設計

場景的基本功能

你知道 Scene 是一個容器,用於存放我們想要在螢幕上渲染的相機、燈光和物件。讓我們看看 Scene 物件的一些基本功能:

新增物件

add(object) 函式用於將物件新增到場景中。

const scene = THREE.Scene()
scene.add(cube) // adds the cube
scene.add(sphere) // adds a sphere

移除物件

remove(object) 函式用於從場景中移除物件。

scene.remove(cube) // removes the last added cube
scene.remove(sphere) // removes a sphere

子物件

scene.children 返回場景中所有物件的陣列,包括相機和燈光。

console.log(scene.children) // outputs all the objects in the scene
console.log(scene.children.length) // outputs number of elements on the
scene

**注意** - 我們可以使用物件的 name 屬性為任何物件命名。名稱對於除錯非常方便,但也可以直接從你的場景中訪問物件。

檢視以下示例。

scene.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js – The scene
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
               Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
         }
         html,
         body {
            height: 100vh;
            width: 100vw;
            background-color: #262626;
            overflow: hidden;
         }
         #btn-conatiner {
            position: absolute;
            top: 0;
            left: 0;
            height: 10vh;
            width: 100%;
         }
         @media screen and (max-width:600px){
            #btn-container{
               display: flex;
               flex-direction: column;
            }
         }
         .btn {
            padding: 5px 15px;
            margin: 5px 15px;
            font-weight: bold;
            text-transform: uppercase;
         }
         .add {
            color: green;
         }
         .rem {
            color: red;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js"></script>
   </head>
   <body>
      <div id="btn-conatiner">
         <button class="btn add">Add Cube</button>
         <button class="btn rem">Remove Cube</button>
      </div>
      <div id="threejs-container"></div>
      <script type="module">
         // Experimenting with different methods of scene
         // add, remove, children, getElementById
         // sizes
         let width = window.innerWidth
         let height = window.innerHeight
         const gui = new dat.GUI()
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // lights
         const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
         scene.add(ambientLight)
         const light = new THREE.PointLight(0xffffff, 0.5)
         light.position.set(-10, 10, -10)
         // for shadow
         light.castShadow = true
         light.shadow.mapSize.width = 1024
         light.shadow.mapSize.height = 1024
         light.shadow.camera.near = 0.1
         light.shadow.camera.far = 1000
         scene.add(light)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000)
         camera.position.set(0, 10, 40)
         camera.lookAt(0, 0, 0)
         gui.add(camera.position, 'z', 10, 200, 1).name('camera-z')
         // plane
         const planeGeometry = new THREE.PlaneGeometry(100, 100)
         const plane = new THREE.Mesh(
            planeGeometry,
            new THREE.MeshPhongMaterial({ color: 0xffffff, side: THREE.DoubleSide })
         )
         plane.rotateX(Math.PI / 2)
         plane.position.y = -1.75
         plane.receiveShadow = true
         scene.add(plane)
         // scene.add
         function addCube() {
            const cubeSize = Math.ceil(Math.random() * 3)
            const cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize)const cubeMaterial = new THREE.MeshLambertMaterial({
               color: Math.random() * 0xffffff
            })
            const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
            cube.castShadow = true
            cube.name = 'cube-' + scene.children.length
            cube.position.x = -30 + Math.round(Math.random() * 50)
            cube.position.y = Math.round(Math.random() * 5)
            cube.position.z = -20 + Math.round(Math.random() * 50)
            scene.add(cube)
         }
         const add = document.querySelector('.add')
         add.addEventListener('click', () => {
            addCube()
            console.log('cube added')
         })
         // scene.remove
         function removeCube() {
            const allChildren = scene.children
            const lastObject = allChildren[allChildren.length - 1]
            if (lastObject.name) {
               scene.remove(lastObject)
            }
         }
         const remove = document.querySelector('.rem')
         remove.addEventListener('click', () => {
            removeCube()
            console.log('cube removed')
         })
         // scene.children
         console.log(scene.children)
         // responsivenesswindow.addEventListener('resize', () => {
            width = window.innerWidth
            height = window.innerHeight
            camera.aspect = width / height
            camera.updateProjectionMatrix()
            renderer.setSize(window.innerWidth, window.innerHeight)
            renderer.render(scene, camera)
         })
         // renderer
         const renderer = new THREE.WebGL1Renderer()
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // animation
         function animate() {
            requestAnimationFrame(animate)
            renderer.render(scene, camera)
         }
         // rendering the scene
         const container = document.querySelector('#threejs-container')
         container.append(renderer.domElement)
         renderer.render(scene, camera)
         animate()
      </script>
   </body>
</html>

開啟你的控制檯以檢視場景中的元素。

Add_Cube

使用 name 屬性

scene.getObjectByName(name) 函式直接從場景中返回具有特定名稱的物件。

你還可以新增另一個引數 - recursive。

scene.getObjectByName(name, recursive)

如果將 recursive 引數設定為 true,Three.js 將搜尋物件的完整樹以查詢具有指定名稱的物件。

向場景新增霧

此屬性允許你設定場景的霧。霧會渲染一種薄霧,隱藏遠處的物件。

scene.fog = new THREE.Fog(0xffffff, 0.015, 100)

這行程式碼定義了白色霧 (0xffffff)。你可以使用前面兩個屬性來調整霧的顯示方式。0.015 值設定 near 屬性,100 值設定 far 屬性。使用這些屬性,你可以確定霧從哪裡開始以及霧的濃度增加速度。

使用 THREE.Fog 物件,霧會線性增加。還有一種不同的方法可以為場景設定霧;為此,請使用以下定義:

scene.fog = new THREE.FogExp2(0xffffff, 0.01)

這次,我們沒有指定 near 和 far,而只是指定顏色 (0xffffff) 和霧的密度 (0.01)。最好對這些屬性進行一些實驗以獲得你想要的效果。

使用 override material 屬性

overrideMaterial 屬性強制場景中的所有物件使用相同的材質。

scene.overrideMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff })

這裡,場景中的所有物件都使用相同的材質,即 MeshLambertMaterial。

**注意** - THREE.Scene 是一種有時也稱為**場景圖**的結構。場景圖是一個可以儲存圖形場景所有必要資訊的結構。在 Three.js 中,這意味著 THREE.Scene 包含渲染所需的所有物件、燈光和其他物件。

Scene_Graph

渲染器

渲染器使用相機和場景中的資訊在螢幕上(即 <canvas> 元素)繪製輸出。

在 Hello cube 應用中,我們使用了 WebGLRenderer。還有一些其他渲染器可用,但 WebGLRenderer 迄今為止是最強大的渲染器,通常也是你唯一需要的渲染器。

注意 − 有一個基於畫布的渲染器,一個基於CSS的渲染器,還有一個基於SVG的渲染器。儘管它們可以工作並渲染簡單的場景,但我並不建議使用它們。它們沒有得到積極的開發,非常佔用CPU,並且缺乏諸如良好的材質支援和陰影等功能。

Three.js - 響應式設計

調整螢幕大小時,您會發現場景沒有響應。使網頁響應式通常是指頁面在從桌上型電腦到平板電腦到手機的不同尺寸的顯示器上都能良好顯示。在本章中,您可以瞭解如何解決Three.js應用程式的一些基本問題。

瀏覽器大小改變時自動調整輸出大小

當您調整瀏覽器大小時,我們必須通知Three.js 元素應該有多寬。對於攝像機,我們需要更新 aspect 屬性(它儲存螢幕的縱橫比),對於渲染器,我們需要更改其大小。

window.addEventListener('resize', () => {
   // update display width and height
   width = window.innerWidth
   height = window.innerHeight
   // update camera aspect
   camera.aspect = width / height
   camera.updateProjectionMatrix()
   // update renderer
   renderer.setSize(width, height)
   renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
   renderer.render(scene, camera)
})

示例

以上程式碼使您的Three.js專案具有響應能力。

resize-browser.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js – Resizing browser</title>
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
            Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
         }
         html,
         body {
            height: 100vh;
            width: 100vw;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js"></script>
   </head>
   <body>
      <div id="threejs-container"></div>
      <script type="module">
         // Adding responsiveness for Three.js
         // sizes
         let width = window.innerWidth
         let height = window.innerHeight
         const gui = new dat.GUI()
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
         camera.position.set(0, 0, 10)
         // cube
         const geometry = new THREE.BoxGeometry(2, 2, 2)
         const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
         })
         const cube = new THREE.Mesh(geometry, material)
         scene.add(cube)
         // responsiveness
         window.addEventListener('resize', () => {
            width = window.innerWidth
            height = window.innerHeight
            camera.aspect = width / height
            camera.updateProjectionMatrix()
            renderer.setSize(window.innerWidth, window.innerHeight)
            renderer.render(scene, camera)
         })
         // renderer
         const renderer = new THREE.WebGL1Renderer()
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // animation
         function animate() {
            requestAnimationFrame(animate)
            cube.rotation.x += 0.005
            cube.rotation.y += 0.01
            renderer.render(scene, camera)
          }
         // rendering the scene
         const container = document.querySelector('#threejs-container')
         container.append(renderer.domElement)
         renderer.render(scene, camera)
         animate()
      </script>
   </body>
</html>

輸出

執行程式碼後,將產生以下輸出:

現在,調整瀏覽器大小。由於響應式設計,物件將始終重新定位到瀏覽器的中心。

抗鋸齒

鋸齒效應是指在邊緣和物體上出現鋸齒狀邊緣或“鋸齒”(也稱為階梯狀線條)(使用畫素渲染)。

Anti Aliasing

示例

antialiasing.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js - Anti-aliasing</title>
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
            Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
         }
         html,
         body {
            height: 100vh;
            width: 100vw;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js"></script>
   </head>
   <body>
      <div id="threejs-container"></div>
      <script type="module">
         // Adding anti-aliasing to Three.js app for removing jaggies
         // sizes
         let width = window.innerWidth
         let height = window.innerHeight
         const gui = new dat.GUI()
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
         camera.position.set(0, 0, 10)
         // cube
         const geometry = new THREE.BoxGeometry(2, 2, 2)
         const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
         })
         const cube = new THREE.Mesh(geometry, material)
         scene.add(cube)
         // responsiveness
         window.addEventListener('resize', () => {
            width = window.innerWidth
            height = window.innerHeight
            camera.aspect = width / height
            camera.updateProjectionMatrix()
            renderer.setSize(window.innerWidth, window.innerHeight)
            renderer.render(scene, camera)
         })
         // renderer - anti-aliasing
         const renderer = new THREE.WebGLRenderer({ antialias: true })
         renderer.physicallyCorrectLights = true
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // animation
         function animate() {
            requestAnimationFrame(animate)
            cube.rotation.x += 0.005
            cube.rotation.y += 0.01
            renderer.render(scene, camera)
         }
         // rendering the scene
         const container = document.querySelector('#threejs-container')
         container.append(renderer.domElement)
         renderer.render(scene, camera)
         animate()
      </script>
   </body>
</html>

輸出

我們的Hello Cube應用程式中的鋸齒看起來像這樣。

Web Renderer

我們可以透過將WebGLRenderer的antialias屬性設定為true來開啟抗鋸齒功能。預設情況下,它是false。在這裡,我們將antialias引數設定為true:

const renderer = new WebGLRenderer({ antialias: true })
renderer.physicallyCorrectLights = true

抗鋸齒後,它看起來很平滑,沒有像下面那樣的鋸齒。

Without Jaggies

physicallyCorrectLights 屬性告訴Three.js 是否使用物理正確的照明模式。預設為false。將其設定為true有助於提高物件的細節。

Three.js - 除錯與統計

使用Dat.GUI

很難不斷試驗變數的值,例如立方體的位置。在這種情況下,假設直到您得到自己喜歡的東西。這是一個緩慢而繁瑣的過程。幸運的是,已經有了一個很好的解決方案,它與Three.js很好地整合,那就是dat.GUI。它允許您建立一個基本的UI元件,可以更改程式碼中的變數。

安裝

要在專案中使用dat.GUI,請從此處下載它,並將