iT邦幫忙

2026 iThome 鐵人賽

DAY 13
0
佛心分享-IT 人自學之術

從空拍到3D展示系列 第 13 篇

Day 13. 搭建 Three.js 開發環境

  • 分享至 

  • xImage
  •  

因為第一次接觸 Three.js,所以先從官網的教學下手,今天只要確定環境都沒問題,(包含 Three.js 的 CDN 路境、創立場景相關的程式碼範例)

確定能執行出預期的結果後,明天再來研究裡面的一些模組、功能
如果已經有接觸過 Three.js 的讀者,今天的文章完全可以跳過

準備步驟

  1. 建立一個資料夾,裡面放 index.html 和 main.js
  2. 用 CDN 方式引入 Three.js,在 html 檔裡加上 ,指向Three.js 官方提供的 CDN 連結,好處是不用透過npm安裝套件或設定打包工具,就能使用Three.js的完整功能

官網例子
https://ithelp.ithome.com.tw/upload/images/20260927/20112674mmPTE80RZ3.png
https://ithelp.ithome.com.tw/upload/images/20260927/20112674ZtG8SICK0z.png

我把以上內容整理成以下程式碼,方便讀者快速複製、貼上測試

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Three.js 測試</title>
    <style>body { margin: 0; }</style>
</head>

<body>
    <script type="importmap">
    {
        "imports": {
            "three": "https://cdn.jsdelivr.net/npm/three@0.149.0/build/three.module.js",
            "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.149.0/examples/jsm/"
        }
    }
    </script>
    <script type="module" src="main.js"></script>

</body>
</html>

產生一個 thress.js 的景: https://threejs.org/manual/#creating-a-scene

# main.js
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

camera.position.z = 5;

function animate(time) {
    cube.rotation.x = time / 2000;
    cube.rotation.y = time / 1000;
    renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

驗證環境正常

這裡要注意,因為index.html裡用src="main.js"引用了另一個獨立檔案,瀏覽器基於安全性限制,不允許直接用雙擊開啟的方式(file://路徑)讀取本地的外部檔案,所以需要透過本地伺服器這種方式開啟,才能正常運作。

  1. 在 Visual Studio Code (VS Code) 安裝 live server (local 建立一個 server, 執行 html 檔案)
  2. 點選 VS Code 右下角 Go Live,它會自動幫你開啟本地端的 port, 和瀏覽器,看到類似以下的畫面,有一個方塊不斷轉動著,代表Three.js環境成功,有使用正確的 CDN 位置
    https://ithelp.ithome.com.tw/upload/images/20260927/20112674lLFJyTmUiK.png

環境確認沒問題後,明天換成把前天的獅山公園模型,載入到這個場景,我預期是把今天的方塊換成自己產出的公園模型。然後著重在程式功能的研究,期待明天會看到更多不一樣的內容~


上一篇
Day12. 動手前的規畫
下一篇
Day 14. 拆解範例程式碼 + 把獅山公園載進 Three.js
系列文
從空拍到3D展示 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言