2026年11月18日 星期三

Three.js 互動程式設計:從 3D 小火車學習 Group、OrbitControls、Raycaster 與曲線動畫

Three.js 互動程式設計:從 3D 小火車學習 Group、OrbitControls、Raycaster 與曲線動畫

《網際網路應用》進階實作|由旋轉立方體邁向真正可互動的 3D 世界

本篇以原創小火車示範四大核心技術,非 Choo-Choo World 原站程式碼。

一、為什麼選擇 3D 小火車?

由單一立方體進入具有多個零件、可操作攝影機、可點選場景物件與沿曲線移動的完整作品。先理解概念,再修改程式。

二、Group:把零件組合成一列火車

使用 THREE.Group() 建立父物件,再把車身、車輪與煙囪加入。移動 train.position 時,所有子物件一起移動。

const train = new THREE.Group();
train.add(body);
train.add(wheel);
scene.add(train);

三、OrbitControls:讓攝影機可以旋轉、縮放與平移

OrbitControls 是 Three.js addons。它修改攝影機位置與目標,並需在動畫迴圈中呼叫 controls.update(),以維持阻尼效果。

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
// 每次渲染前執行 controls.update();

四、Raycaster:用滑鼠選取場景物件

將 pointer 位置換算成 Canvas 的標準化裝置座標(-1 到 1),再用 Raycaster 檢測碰撞。滑鼠拖曳與點擊應區分,避免轉動視角時誤選。

raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(markers);

五、Curve:讓火車沿鐵軌前進

CatmullRomCurve3 由控制點生成平滑曲線;getPointAt() 取得位置,getTangentAt() 取得方向。以時間差更新進度,避免 FPS 不同造成速度差異。

const pos = path.getPointAt(progress);
const tangent = path.getTangentAt(progress);
train.position.copy(pos);
train.rotation.y = Math.atan2(tangent.x, tangent.z);

六、Animation Loop:更新狀態並繪製畫面

動畫迴圈依序讀取時間差、更新火車位置與朝向、更新 OrbitControls、執行 renderer.render(scene,camera)。

七、燈光與日夜切換

透過 Scene.background、HemisphereLight 與 DirectionalLight 的設定切換白天及夜晚,觀察材質與光照的關係。

八、學生動手挑戰

練習一:增加車廂並透過 Group 一起移動。練習二:新增 3D 樹木。練習三:更改曲線控制點。練習四:替選中的標記增加旋轉功能。練習五:研究如何讓編輯標記真正改變火車路線。

九、完整可執行 HTML 原始碼

將以下程式存成 train.html,使用本機 HTTP 伺服器執行,例如 python -m http.server 8000,瀏覽 http://localhost:8000/train.html。程式需要連線至 Three.js CDN。

Blogger 通常不適合直接執行含 ES Module 的大型 3D 專案。建議將範例 HTML 放在 GitHub Pages 或其他靜態網站,部落格放程式碼與操作連結。

<!DOCTYPE html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 3D 小火車互動實作</title>
<style>body{margin:0;font:15px system-ui,'Noto Sans TC',sans-serif;background:#0f1e30;color:#f3f8ff}#stage{width:100%;height: min(72vh,620px);min-height:360px}#panel{display:flex;gap:9px;flex-wrap:wrap;padding:12px;background:#182d43;align-items:center}button{padding:9px 12px;border:1px solid #7ba4bd;border-radius:7px;background:#254967;color:white;cursor:pointer}button:hover{background:#36709b}#status{margin-left:auto;font-size:13px}#help{padding:10px 14px;color:#c8d9e9;font-size:13px}#error{color:#ffcfb3;padding:8px}</style>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.181.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.181.0/examples/jsm/"}}</script></head><body>
<div id="panel"><button id="play">暫停火車</button><button id="add">增加鐵軌標記</button><button id="remove">移除標記</button><button id="day">切換夜晚</button><button id="reset">重設視角</button><label>速度 <input id="speed" type="range" min="0" max="3" step="0.1" value="1"></label><span id="status">準備中</span></div>
<div id="stage"></div><div id="help">滑鼠左鍵拖曳旋轉視角、滾輪縮放、右鍵拖曳平移。點選場景中的鐵軌標記可選取;按「增加鐵軌標記」後點選地面新增。標記是教學用編輯物件,不會改變火車的預設行駛路徑。</div><div id="error"></div>
<script type="module">
import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
const stage=document.getElementById('stage');
const scene=new THREE.Scene();scene.background=new THREE.Color(0xa8d9f5);
const camera=new THREE.PerspectiveCamera(55,1,.1,150);camera.position.set(10,9,12);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));stage.appendChild(renderer.domElement);
const controls=new OrbitControls(camera,renderer.domElement);controls.enableDamping=true;controls.target.set(0,0,0);
const ambient=new THREE.HemisphereLight(0xffffff,0x58754e,2);scene.add(ambient);
const sun=new THREE.DirectionalLight(0xffffff,2.4);sun.position.set(6,12,8);scene.add(sun);
const ground=new THREE.Mesh(new THREE.PlaneGeometry(50,50),new THREE.MeshStandardMaterial({color:0x6eae77,roughness:1}));ground.rotation.x=-Math.PI/2;ground.position.y=-.08;scene.add(ground);
const grid=new THREE.GridHelper(32,32,0x4e8160,0x7cae87);grid.position.y=-.065;scene.add(grid);
// 由多個點建立平滑封閉路徑
const path=new THREE.CatmullRomCurve3([new THREE.Vector3(-5,0,-2),new THREE.Vector3(-3,0,3),new THREE.Vector3(2,0,4),new THREE.Vector3(5,0,0),new THREE.Vector3(2,0,-4)],true,'catmullrom',.4);
const points=path.getSpacedPoints(220);const trackGeometry=new THREE.BufferGeometry().setFromPoints(points.map(p=>new THREE.Vector3(p.x,.03,p.z)));
const rail=new THREE.LineLoop(trackGeometry,new THREE.LineBasicMaterial({color:0x4b392e}));scene.add(rail);
const sleeperMat=new THREE.MeshStandardMaterial({color:0x8b5e3c});const sleeperGeo=new THREE.BoxGeometry(.65,.09,.24);
for(let i=0;i<100;i++){const t=i/100,p=path.getPointAt(t),d=path.getTangentAt(t);const sleeper=new THREE.Mesh(sleeperGeo,sleeperMat);sleeper.position.set(p.x,.015,p.z);sleeper.rotation.y=Math.atan2(d.x,d.z);scene.add(sleeper)}
// Group 將車身、煙囪、車輪整合成一列火車
const train=new THREE.Group();const red=new THREE.MeshStandardMaterial({color:0xe75a43});const blue=new THREE.MeshStandardMaterial({color:0x3b82b6});const black=new THREE.MeshStandardMaterial({color:0x252e39});
function box(w,h,d,mat,x,y,z){const m=new THREE.Mesh(new THREE.BoxGeometry(w,h,d),mat);m.position.set(x,y,z);train.add(m);return m}
box(1.25,.65,1.8,red,0,.58,0);box(1.05,.8,.7,blue,0,1.13,-.45);box(.4,.55,.4,black,0,1.2,.5);
const wheelGeo=new THREE.CylinderGeometry(.24,.24,.12,20);for(const x of [-.7,.7])for(const z of [-.58,.58]){const wheel=new THREE.Mesh(wheelGeo,black);wheel.rotation.z=Math.PI/2;wheel.position.set(x,.26,z);train.add(wheel)}scene.add(train);
const markers=[];const markerGeo=new THREE.BoxGeometry(.48,.12,.8);const normalMat=new THREE.MeshStandardMaterial({color:0xf8c75b});const selectedMat=new THREE.MeshStandardMaterial({color:0xff6b6b});let selected=null,placing=false;
function addMarker(x,z){const m=new THREE.Mesh(markerGeo,normalMat);m.position.set(x,.1,z);m.userData.isMarker=true;scene.add(m);markers.push(m);select(m)}
function select(m){if(selected)selected.material=normalMat;selected=m;if(m)m.material=selectedMat}
const raycaster=new THREE.Raycaster(),pointer=new THREE.Vector2();let pointerDown=null;
renderer.domElement.addEventListener('pointerdown',e=>{pointerDown={x:e.clientX,y:e.clientY}});
renderer.domElement.addEventListener('pointerup',e=>{if(!pointerDown||Math.hypot(e.clientX-pointerDown.x,e.clientY-pointerDown.y)>5)return;const r=renderer.domElement.getBoundingClientRect();pointer.set(((e.clientX-r.left)/r.width)*2-1,-((e.clientY-r.top)/r.height)*2+1);raycaster.setFromCamera(pointer,camera);if(placing){const hits=raycaster.intersectObject(ground);if(hits.length)addMarker(hits[0].point.x,hits[0].point.z);placing=false;document.getElementById('add').textContent='增加鐵軌標記'}else{const hits=raycaster.intersectObjects(markers);select(hits.length?hits[0].object:null)}});
let running=true,night=false,progress=0;const clock=new THREE.Clock();
document.getElementById('play').onclick=()=>{running=!running;document.getElementById('play').textContent=running?'暫停火車':'啟動火車'};
document.getElementById('add').onclick=()=>{placing=!placing;document.getElementById('add').textContent=placing?'請點選地面':'增加鐵軌標記'};
document.getElementById('remove').onclick=()=>{if(!selected)return;scene.remove(selected);markers.splice(markers.indexOf(selected),1);selected.geometry.dispose();select(null)};
document.getElementById('day').onclick=()=>{night=!night;scene.background=new THREE.Color(night?0x101b34:0xa8d9f5);ambient.intensity=night?.35:2;sun.intensity=night?.2:2.4;document.getElementById('day').textContent=night?'切換白天':'切換夜晚'};
document.getElementById('reset').onclick=()=>{camera.position.set(10,9,12);controls.target.set(0,0,0);controls.update()};
function resize(){const w=stage.clientWidth,h=stage.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h,false)}new ResizeObserver(resize).observe(stage);resize();
renderer.setAnimationLoop(()=>{const delta=Math.min(clock.getDelta(),.05),speed=Number(document.getElementById('speed').value);if(running)progress=(progress+delta*speed*.035)%1;const pos=path.getPointAt(progress),tangent=path.getTangentAt(progress);train.position.set(pos.x,.04,pos.z);train.rotation.y=Math.atan2(tangent.x,tangent.z);controls.update();renderer.render(scene,camera);document.getElementById('status').textContent=`進度 ${(progress*100).toFixed(0)}% · 標記 ${markers.length} 個`});
</script></body></html>

十、延伸思考

為什麼車身與車輪適合放在同一個 Group?為什麼 Raycaster 需要換算滑鼠座標?為什麼沿曲線行駛還需要計算切線方向?為什麼要使用 delta time?

參考:Three.js 官方文件、Choo-Choo World。

從 Choo-Choo World 認識 Three.js 互動式 3D 世界的十大技術

從 Choo-Choo World 認識 Three.js 互動式 3D 世界的十大技術

從一個可以自由拼接鐵軌、觀看火車行駛的互動網站,認識 Three.js 如何處理場景、物件、攝影機、滑鼠選取、曲線動畫與效能最佳化。

適用:科技大學《網際網路應用》與 Three.js 入門延伸課程

開啟 Choo-Choo World 體驗網站

一、為什麼選擇 Choo-Choo World?

Choo-Choo World 是 Lusion 製作的互動式 3D 火車軌道建構網站。使用者可以拼接軌道、控制火車播放、切換日夜及調整觀看視角。作品相關介紹提及 Three.js、Angular、Blender、Cinema 4D 與紋理最佳化等技術。

閱讀提醒:本文的程式碼是為了理解技術而自行設計的教學示例,不是 Choo-Choo World 原始碼。網站功能與可能採用的 Three.js API 應分開理解;部分程式片段需置於已建立 scene、camera、renderer 等變數的專案中。

二、十大技術總覽

技術學習重點
01 Scene 與 Scene GraphScene、Group、Mesh、position
02 3D 座標、旋轉與方向Vector3、Euler、Quaternion
03 Camera 與 OrbitControlsPerspectiveCamera、OrbitControls
04 Geometry、Material 與 GroupBoxGeometry、CylinderGeometry、MeshStandardMaterial
05 Raycaster 與 Pointer EventsRaycaster、Vector2、pointerdown
06 Curve 與動畫CatmullRomCurve3、getPointAt、getTangentAt
07 Animation Loop 與 Delta TimesetAnimationLoop、Clock、delta
08 Light、Texture 與日夜場景AmbientLight、DirectionalLight、Texture
09 資料結構、Undo 與場景分享JSON、URLSearchParams、localStorage
10 效能最佳化與跨裝置操作InstancedMesh、LOD、Texture Baking

三、逐項解析與程式練習

01|Scene 與 Scene Graph:建立完整的 3D 世界

場景不是一張圖片,而是由地面、樹木、鐵軌、火車與光源等物件構成的階層結構。Group 可以把車身和車輪視為一個整體。

核心 API:Scene、Group、Mesh、position

const scene = new THREE.Scene();
const train = new THREE.Group();
const body = new THREE.Mesh(
  new THREE.BoxGeometry(2, 0.8, 1),
  new THREE.MeshStandardMaterial({ color: 0xe85d3f })
);
train.add(body);
scene.add(train);
train.position.set(0, 0.5, 0);

學生練習:把車身換成兩節車廂,觀察移動父群組與移動單一車廂的差異。

02|3D 座標、旋轉與方向:鐵軌為什麼能接起來?

在三維世界中,X、Y、Z 分別描述左右、上下及前後。旋轉角度使用弧度;軌道拼接還需要考慮端點位置與朝向。

核心 API:Vector3、Euler、Quaternion

const track = new THREE.Group();
track.position.set(2, 0, -1);
track.rotation.y = Math.PI / 2; // 旋轉 90 度
scene.add(track);
const endpoint = new THREE.Vector3(1, 0, 0);
track.localToWorld(endpoint);
console.log('世界座標端點', endpoint);

學生練習:比較局部座標與世界座標;試著讓兩段直線鐵軌的端點對齊。

03|Camera 與 OrbitControls:自由觀看火車世界

網站支援旋轉、縮放與平移視角。教學可使用 OrbitControls 建立類似互動,但不能據此斷定原網站使用相同的控制器。

核心 API:PerspectiveCamera、OrbitControls

import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const camera = new THREE.PerspectiveCamera(55, width / height, 0.1, 100);
camera.position.set(5, 6, 9);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.target.set(0, 0, 0);
// 在動畫迴圈內呼叫 controls.update();

學生練習:改變 camera.position 與 controls.target,觀察視角與注視目標的差異。

04|Geometry、Material 與 Group:組合小火車

Geometry 定義形狀,Material 定義表面,Mesh 把兩者組合;Group 則用來組織多個 Mesh。

核心 API:BoxGeometry、CylinderGeometry、MeshStandardMaterial

const wheels = new THREE.Group();
for (const x of [-0.65, 0.65]) {
  const wheel = new THREE.Mesh(
    new THREE.CylinderGeometry(0.25, 0.25, 0.15, 24),
    new THREE.MeshStandardMaterial({ color: 0x222222 })
  );
  wheel.rotation.z = Math.PI / 2;
  wheel.position.set(x, -0.35, 0);
  wheels.add(wheel);
}
train.add(wheels);

學生練習:替火車加入車窗、煙囪與不同顏色的車輪。

05|Raycaster 與 Pointer Events:用滑鼠選取鐵軌

在 3D 編輯器中,滑鼠的二維位置需要換算成攝影機射線,才能找到被點擊的物件。這是可用來重現選取操作的教學方法。

核心 API:Raycaster、Vector2、pointerdown

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (event) => {
  const rect = renderer.domElement.getBoundingClientRect();
  pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  raycaster.setFromCamera(pointer, camera);
  const hits = raycaster.intersectObjects(scene.children, true);
  if (hits.length) console.log('選到:', hits[0].object.name);
});

學生練習:讓被點選的立方體變色,並思考如何避免點擊地面時誤選其他物件。

06|Curve 與動畫:讓火車沿著鐵軌行駛

火車需要沿著路徑移動,同時調整車頭方向。Three.js 的 Curve 可取得路徑位置及切線;實際拼軌系統還需要處理軌道連接。

核心 API:CatmullRomCurve3、getPointAt、getTangentAt

const path = new THREE.CatmullRomCurve3([
  new THREE.Vector3(-3, 0, 0),
  new THREE.Vector3(-1, 0, 2),
  new THREE.Vector3(2, 0, 2),
  new THREE.Vector3(4, 0, 0)
]);
let progress = 0;
function updateTrain(delta) {
  progress = (progress + delta * 0.08) % 1;
  train.position.copy(path.getPointAt(progress));
  const tangent = path.getTangentAt(progress);
  train.rotation.y = Math.atan2(tangent.x, tangent.z);
}

學生練習:調整控制點,觀察彎道形狀;比較 getPoint() 與 getPointAt()。

07|Animation Loop 與 Delta Time:讓動畫平順

連續動畫的核心是每次更新位置、方向,再重新渲染。使用時間差可減少不同裝置影格率造成的速度差異。

核心 API:setAnimationLoop、Clock、delta

const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
  const delta = Math.min(clock.getDelta(), 0.05);
  updateTrain(delta);
  controls.update();
  renderer.render(scene, camera);
});

學生練習:嘗試移除 delta,觀察不同影格率下動畫速度為何可能改變。

08|Light、Texture 與日夜場景

網站有日夜切換;技術介紹提到使用烘焙紋理。初學者可先透過背景色與光照強度學習日夜差異,再理解 Texture Baking 的最佳化意義。

核心 API:AmbientLight、DirectionalLight、Texture

const sun = new THREE.DirectionalLight(0xffffff, 2);
scene.add(sun);
function setNight(isNight) {
  scene.background = new THREE.Color(isNight ? 0x101a35 : 0x87ceeb);
  sun.intensity = isNight ? 0.2 : 2;
}
setNight(false);

學生練習:設計白天與夜晚按鈕,記錄背景與光源改變後的視覺差異。

09|資料結構、Undo 與場景分享

網站能編輯與分享鐵軌作品。教學可將軌道類型、座標及旋轉角度轉成 JSON,並使用 URL 或本機儲存。網址中的 DATA 參數不能直接當作已知編碼規則。

核心 API:JSON、URLSearchParams、localStorage

const tracks = [
  { type: 'straight', x: 0, z: 0, angle: 0 },
  { type: 'curve', x: 1, z: 0, angle: 90 }
];
const saved = JSON.stringify(tracks);
localStorage.setItem('myTracks', saved);
const restored = JSON.parse(localStorage.getItem('myTracks') || '[]');
console.log(restored);

學生練習:增加「新增一段」、「復原上一段」、「清空場景」三種功能。

10|效能最佳化與跨裝置操作

複雜 3D 場景需要考慮模型面數、紋理、繪製呼叫與手機效能。重複物件可評估 InstancedMesh;也可限制像素比。

核心 API:InstancedMesh、LOD、Texture Baking

renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
// 重複的相同幾何物件可考慮 InstancedMesh
const trees = new THREE.InstancedMesh(treeGeometry, treeMaterial, 100);
const matrix = new THREE.Matrix4();
for (let i = 0; i < 100; i++) {
  matrix.makeTranslation((i % 10) * 2, 0, Math.floor(i / 10) * 2);
  trees.setMatrixAt(i, matrix);
}
trees.instanceMatrix.needsUpdate = true;
scene.add(trees);

學生練習:比較 100 個獨立 Mesh 與一個 InstancedMesh 的繪製效能;先建立 treeGeometry、treeMaterial。

四、實際操作觀察表

操作觀察問題
拖曳與縮放視角是攝影機移動,還是場景中的物件移動?
新增彎曲鐵軌每一段軌道如何決定位置、角度與接點?
啟動火車火車如何依路徑更新位置與方向?
切換日夜哪些光照、背景及材質效果發生變化?
分享作品如何用資料描述場景,讓另一台電腦重建?

五、建議的課程安排

第一堂課(2 小時):體驗網站、認識 Scene Graph、Group、Camera 與 3D 座標。第二堂課(2 小時):練習 Raycaster、曲線路徑與動畫。第三堂課(2 小時):日夜場景、JSON 儲存與效能最佳化。

六、課後思考

  1. 為什麼火車適合使用 Group,而不只是一個 Mesh?
  2. Raycaster 與一般 HTML 按鈕事件有何不同?
  3. 如何同時更新火車位置與車頭方向?
  4. 為什麼動畫速度需要考慮 delta time?
  5. 為什麼大量重複物件需要效能最佳化?

七、延伸閱讀

Choo-Choo World 官方網站|Three.js 官方基礎教學|Three.js API 文件|Choo-Choo World 技術介紹

結語:Three.js 的學習可以從一個旋轉立方體開始,但真正的互動世界需要把物件組合、視角、事件、路徑、動畫與資料結構連結起來。理解這十大技術,將有助於學生進一步自行設計 3D 互動網頁。

深入認識 Three.js 程式基本架構:從旋轉立方體理解 3D 網頁

深入認識 Three.js 程式基本架構:從旋轉立方體理解 3D 網頁

《網際網路應用》實作教學|Scene、Camera、Renderer、Mesh、Light、Animation Loop

本篇從一段短短的 Three.js 程式出發,逐行拆解 3D 網頁如何運作,再補成一份可以獨立執行的完整 HTML,透過觀念解析、完整程式與動手實驗,深入理解 Three.js 的核心架構。

一、先看原始程式

import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(55, width / height, 0.1, 100);
const renderer = new THREE.WebGLRenderer({antialias:true});
const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1,1,1),
  new THREE.MeshStandardMaterial({color:0x38bdf8})
);
scene.add(cube);
renderer.setAnimationLoop(() => {
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
});

重要:這段是核心示意,不是完整網頁。width、height 尚未定義,攝影機未移動,Canvas 尚未插入網頁,也沒有燈光。因此直接貼上可能看不到預期的藍色立方體。

二、Three.js 的六個核心角色

元件角色生活比喻
Scene管理場景中的物件攝影棚
Camera決定觀看位置與角度攝影機
Renderer把 3D 場景繪到 Canvas影像輸出
Geometry決定形狀道具骨架
Material / Mesh決定外觀並組成物件道具表面與成品
Animation Loop更新狀態並重新繪圖連續播放影格

三、逐行理解程式架構

01|匯入函式庫

import * as THREE from 'three'; 使用 ES Module 匯入 Three.js。THREE 是命名空間,方便使用 THREE.Scene 等類別。瀏覽器必須能解析 three,因此完整範例使用 Import Map 指向 CDN。

02|Scene:建立 3D 世界

new THREE.Scene() 是場景容器。scene.add(cube) 只是把物件加入場景樹,不會直接把它畫到螢幕。Scene 也可以放光源、模型與群組。

03|Camera:從哪裡看?

new THREE.PerspectiveCamera(55, width / height, 0.1, 100) 的四個參數依序是垂直視角 FOV(度)、寬高比、近裁切面、遠裁切面。預設攝影機位於原點,應使用 camera.position.set(0,0,4) 移開,才能看見同樣位於原點的立方體。

04|Renderer:把 3D 畫到網頁

new THREE.WebGLRenderer({antialias:true}) 建立 WebGL 渲染器;renderer.setSize() 設定畫布大小;document.body.appendChild(renderer.domElement) 將 Canvas 加入 HTML。renderer.render(scene,camera) 才是真正繪製畫面。

05|Geometry + Material = Mesh

BoxGeometry(1,1,1) 決定立方體寬、高、深;MeshStandardMaterial({color:0x38bdf8}) 決定表面外觀;new THREE.Mesh(geometry,material) 將兩者結合成可加入場景的物件。

06|Light:為什麼需要燈光?

MeshStandardMaterial 會依照光照計算表面顏色;若場景沒有光源,物件可能很暗或近乎黑色。入門可用 AmbientLight 加上 DirectionalLight。若使用 MeshBasicMaterial,則不受場景光源影響。

07|Animation Loop:為什麼立方體會轉?

renderer.setAnimationLoop(callback) 反覆執行回呼函式。每次更新 cube.rotation.y,再呼叫 renderer.render()。旋轉角度單位是弧度,0.01 代表每影格增加 0.01 弧度,而不是每秒。

08|Delta Time:不同電腦速度一致

const delta = clock.getDelta() 取得兩次更新之間的秒數。cube.rotation.y += delta * rotationSpeed 可設定近似每秒固定角速度。範例將 delta 上限設為 0.05 秒,避免切換分頁後一次跳動過大。

09|Resize:視窗大小改變怎麼辦?

當視窗比例改變,需更新 camera.aspect、呼叫 camera.updateProjectionMatrix(),再以 renderer.setSize() 調整畫布,避免畫面拉伸或裁切。

四、可直接執行的完整 HTML 程式

將以下完整內容存成 index.html,透過本機 HTTP 伺服器開啟。這份程式已補上尺寸、攝影機位置、燈光、Canvas、動畫時間差與視窗縮放。

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Three.js 旋轉立方體</title>
  <style>
    body { margin: 0; background: #0f172a; }
  </style>
  <script type="importmap">
  {
    "imports": {
      "three": "https://cdn.jsdelivr.net/npm/three@0.181.0/build/three.module.js"
    }
  }
  </script>
</head>
<body>
<script type="module">
import * as THREE from 'three';

// 1. Scene:建立場景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0f172a);

// 2. Camera:建立透視攝影機
const camera = new THREE.PerspectiveCamera(
  55, window.innerWidth / window.innerHeight, 0.1, 100
);
camera.position.set(0, 0, 4);

// 3. Renderer:建立渲染器並插入網頁
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);

// 4. Geometry + Material = Mesh
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({
  color: 0x38bdf8, roughness: 0.5, metalness: 0.1
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 5. Light:標準材質需要光源
const ambient = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xffffff, 2);
sun.position.set(3, 4, 5);
scene.add(sun);

// 6. Animation Loop:使用時間差避免 FPS 影響速度
const clock = new THREE.Clock();
let rotationSpeed = 1.0; // 每秒約 1 弧度
let isPlaying = true;
renderer.setAnimationLoop(() => {
  const delta = Math.min(clock.getDelta(), 0.05);
  if (isPlaying) {
    cube.rotation.y += delta * rotationSpeed;
    cube.rotation.x += delta * 0.3;
  }
  renderer.render(scene, camera);
});

// 7. 視窗改變時同步更新相機比例與畫布尺寸
window.addEventListener('resize', () => {
  const width = window.innerWidth;
  const height = window.innerHeight;
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height);
});
</script>
</body>
</html>

五、動手做:五個小實驗

  1. 把 camera.position.set(0,0,4) 改成 (0,0,8),觀察立方體大小。
  2. 將 BoxGeometry(1,1,1) 改成 BoxGeometry(2,1,1),觀察長方體。
  3. 將材質顏色改成 0xff8844,觀察色彩變化。
  4. 註解掉兩種光源,再比較 MeshStandardMaterial 與 MeshBasicMaterial。
  5. 把 rotationSpeed 設為 0、0.5、2,記錄每種速度的效果。

六、深入理解 3D 座標、物件與動畫

1. 三維座標系統

Three.js 使用 X、Y、Z 三個軸描述空間位置。X 軸代表左右,Y 軸代表上下,Z 軸代表前後。物件預設位於原點 (0,0,0),攝影機預設朝向負 Z 方向。

cube.position.set(1, 0, 0); // 向右移動
cube.rotation.y = Math.PI / 4; // 繞 Y 軸旋轉 45 度
cube.scale.set(2, 1, 1); // X 方向放大兩倍

2. Scene Graph 場景階層

Scene 不只是物件清單,也是父子關係的樹狀結構。可以使用 Group 將多個物件組合,對群組移動、旋轉或縮放時,子物件會跟著變化。

const group = new THREE.Group();
group.add(cube);
scene.add(group);
group.rotation.y += 0.01;

3. 為什麼要使用時間差 delta?

若每影格旋轉 0.01 弧度,60 FPS 與 120 FPS 的轉速會不同。使用時間差(秒)乘上角速度(弧度/秒),能讓不同電腦上的動畫更接近相同速度。

const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
  const delta = clock.getDelta();
  cube.rotation.y += delta * 1.0;
  renderer.render(scene, camera);
});

4. 繪製與更新是不同工作

cube.rotation.y 是修改物件狀態;renderer.render(scene, camera) 則是依據當下場景與攝影機重新繪製畫面。只改變物件資料而不重新渲染,通常不會在螢幕上看到更新。

七、常見問題與除錯

問題檢查方式
畫面空白開啟 F12 Console,確認 CDN、Import Map、WebGL 與程式錯誤
物件看不到確認 Camera 位置、物件位置、Near/Far 與 render 呼叫
物件黑色確認標準材質是否有光源
畫面比例變形確認 resize 事件與 updateProjectionMatrix()
不同電腦速度不同使用 deltaTime 而非固定每影格增加角度

八、課堂思考題

  1. scene.add(cube) 與 renderer.render(scene,camera) 差在哪裡?
  2. 為何建立攝影機後,還要設定 camera.position?
  3. Geometry、Material、Mesh 三者有何關係?
  4. 為何 rotation.y += 0.01 不是固定的每秒角速度?
  5. 如何使用 Group 讓兩個立方體一起旋轉?

九、延伸閱讀

Three.js 3D 入門文章|Three.js 官方 Creating a Scene|Three.js 官方文件

教學提醒:Blogger 可能限制或清理文章內的 JavaScript,因此本篇以「完整程式碼展示」為主。請將完整 HTML 存成獨立檔案測試,再依需要部署至靜態網站並連結到 Blogger。

2026年11月17日 星期二

Three.js 從零開始:六個有趣的 3D 網頁互動小範例

Three.js 從零開始:六個有趣的 3D 網頁互動小範例

從旋轉立方體、幾何積木、燈光、風車、智慧養殖魚池到小機器人,循序學會 JavaScript 3D 動畫,並為下一階段 MQTT × Raspberry Pi Pico 2 W 虛實整合打下基礎。

一、為什麼要學 Three.js?

Three.js 讓 JavaScript 可以建立 Scene(場景)、Camera(攝影機)、Renderer(渲染器)、Mesh(物件)與 Light(光源),透過動畫迴圈讓 3D 物件動起來。這六個練習先在瀏覽器本地控制,不需要 MQTT 或硬體。每個範例均附完整可獨立執行的 HTML 原始碼,包含 Three.js 載入、場景建立、動畫及操作控制。

二、課前準備

使用 Chrome 或 Edge、文字編輯器與 Python 3。將下方六個完整程式碼分別儲存成 HTML 檔案,放在同一個資料夾,開啟終端機執行:

python -m http.server 8000

瀏覽器輸入 http://localhost:8000/01_旋轉立方體.html。需要網路連線以載入 Three.js CDN。Blogger 的程式碼區塊僅用於閱讀;完整互動作品建議放在獨立 HTML 網頁,透過 iframe 嵌入。

三、Three.js 程式基本架構

import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(55, width / height, 0.1, 100);
const renderer = new THREE.WebGLRenderer({antialias:true});
const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1,1,1),
  new THREE.MeshStandardMaterial({color:0x38bdf8})
);
scene.add(cube);
renderer.setAnimationLoop(() => {
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
});

其中 Mesh 結合幾何形狀與材質;rotation 控制旋轉;setAnimationLoop 讓場景持續更新。完整範例還會處理光源、畫面尺寸與攝影機位置。

範例 1:第一個 3D 立方體

建立 Mesh 並透過動畫迴圈旋轉。先執行,再觀察下列關鍵程式。

程式重點

const cube=add(new THREE.BoxGeometry(2,2,2),0x38bdf8);
update=(dt)=>{cube.rotation.x+=dt*.7;cube.rotation.y+=dt};

完整 HTML 程式碼(可直接另存為 01_旋轉立方體.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const cube=add(new THREE.BoxGeometry(2,2,2),0x38bdf8);
update=(dt)=>{cube.rotation.x+=dt*.7;cube.rotation.y+=dt};
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:改變立方體顏色、大小與旋轉方向。

獨立檔案:01_旋轉立方體.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

範例 2:幾何積木遊樂場

認識 BoxGeometry、SphereGeometry 與 ConeGeometry。先執行,再觀察下列關鍵程式。

程式重點

const shapes=[add(new THREE.BoxGeometry(1.5,1.5,1.5),0x38bdf8,-2,0,0),add(new THREE.SphereGeometry(.9,32,20),0xfbbf24,0,0,0),add(new THREE.ConeGeometry(.9,1.8,32),0xfb7185,2,0,0)];
update=dt=>shapes.forEach((s,i)=>s.rotation.y+=dt*(i+1)*.35);

完整 HTML 程式碼(可直接另存為 02_幾何積木.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const shapes=[add(new THREE.BoxGeometry(1.5,1.5,1.5),0x38bdf8,-2,0,0),add(new THREE.SphereGeometry(.9,32,20),0xfbbf24,0,0,0),add(new THREE.ConeGeometry(.9,1.8,32),0xfb7185,2,0,0)];
update=dt=>shapes.forEach((s,i)=>s.rotation.y+=dt*(i+1)*.35);
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:增加一種幾何物件,並調整物件的位置。

獨立檔案:02_幾何積木.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

範例 3:智慧燈光控制

用按鈕與滑桿調整 DirectionalLight。先執行,再觀察下列關鍵程式。

程式重點

const sphere=add(new THREE.SphereGeometry(1.3,48,32),0x67e8f9);let enabled=true;button("開/關方向光",()=>{enabled=!enabled;sun.visible=enabled});slider("亮度",0,5,2,v=>sun.intensity=v);update=dt=>sphere.rotation.y+=dt*.4;

完整 HTML 程式碼(可直接另存為 03_燈光控制.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const sphere=add(new THREE.SphereGeometry(1.3,48,32),0x67e8f9);let enabled=true;button("開/關方向光",()=>{enabled=!enabled;sun.visible=enabled});slider("亮度",0,5,2,v=>sun.intensity=v);update=dt=>sphere.rotation.y+=dt*.4;
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:讓燈光變成紅色,並觀察材質的變化。

獨立檔案:03_燈光控制.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

範例 4:智慧風車

使用 Group 組合物件並調整旋轉速度。先執行,再觀察下列關鍵程式。

程式重點

const tower=add(new THREE.CylinderGeometry(.18,.32,3,16),0x94a3b8,0,-.8);const rotor=new THREE.Group();rotor.position.set(0,.8,.35);scene.add(rotor);for(let i=0;i<4;i++){const blade=add(new THREE.BoxGeometry(.35,1.7,.12),0x38bdf8,0,.85,0,rotor);blade.rotation.z=i*Math.PI/2;blade.position.set(-Math.sin(i*Math.PI/2)*.85,Math.cos(i*Math.PI/2)*.85,0)}let speed=2,play=true;slider("風速",0,10,2,v=>speed=v);button("啟動/暫停",()=>play=!play);update=dt=>{if(play)rotor.rotation.z-=speed*dt};

完整 HTML 程式碼(可直接另存為 04_風車.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const tower=add(new THREE.CylinderGeometry(.18,.32,3,16),0x94a3b8,0,-.8);const rotor=new THREE.Group();rotor.position.set(0,.8,.35);scene.add(rotor);for(let i=0;i<4;i++){const blade=add(new THREE.BoxGeometry(.35,1.7,.12),0x38bdf8,0,.85,0,rotor);blade.rotation.z=i*Math.PI/2;blade.position.set(-Math.sin(i*Math.PI/2)*.85,Math.cos(i*Math.PI/2)*.85,0)}let speed=2,play=true;slider("風速",0,10,2,v=>speed=v);button("啟動/暫停",()=>play=!play);update=dt=>{if(play)rotor.rotation.z-=speed*dt};
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:修改風車葉片數量與最高速度。

獨立檔案:04_風車.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

範例 5:智慧養殖魚池

以水溫模擬魚群游動速度(非真實生理模型)。先執行,再觀察下列關鍵程式。

程式重點

const pond=add(new THREE.CylinderGeometry(2.8,2.8,.18,64),0x0284c7,0,-1.5);const fish=[];for(let i=0;i<5;i++){const g=new THREE.Group();scene.add(g);const body=add(new THREE.SphereGeometry(.27,16,12),[0xfbbf24,0xfb7185,0x34d399][i%3],0,0,0,g);body.scale.set(1.5,.65,.65);const tail=add(new THREE.ConeGeometry(.2,.5,3),0xffffff,-.5,0,0,g);tail.rotation.z=Math.PI/2;fish.push(g)}let temp=26,t=0;slider("水溫 ℃",15,35,26,v=>temp=v);update=dt=>{t+=dt*(.3+(temp-15)*.035);fish.forEach((f,i)=>{const a=t+i*Math.PI*2/5;f.position.set(Math.cos(a)*1.6,-.8+Math.sin(a*2)*.15,Math.sin(a)*1.6);f.rotation.y=-a-Math.PI/2})};

完整 HTML 程式碼(可直接另存為 05_智慧魚池.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const pond=add(new THREE.CylinderGeometry(2.8,2.8,.18,64),0x0284c7,0,-1.5);const fish=[];for(let i=0;i<5;i++){const g=new THREE.Group();scene.add(g);const body=add(new THREE.SphereGeometry(.27,16,12),[0xfbbf24,0xfb7185,0x34d399][i%3],0,0,0,g);body.scale.set(1.5,.65,.65);const tail=add(new THREE.ConeGeometry(.2,.5,3),0xffffff,-.5,0,0,g);tail.rotation.z=Math.PI/2;fish.push(g)}let temp=26,t=0;slider("水溫 ℃",15,35,26,v=>temp=v);update=dt=>{t+=dt*(.3+(temp-15)*.035);fish.forEach((f,i)=>{const a=t+i*Math.PI*2/5;f.position.set(Math.cos(a)*1.6,-.8+Math.sin(a*2)*.15,Math.sin(a)*1.6);f.rotation.y=-a-Math.PI/2})};
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:新增魚隻,觀察水溫如何改變動畫速度;注意這只是示意模型。

獨立檔案:05_智慧魚池.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

範例 6:3D 小機器人

用方向鍵與按鈕移動機器人。先執行,再觀察下列關鍵程式。

程式重點

const robot=new THREE.Group();scene.add(robot);add(new THREE.BoxGeometry(1,1,.7),0x38bdf8,0,0,0,robot);add(new THREE.BoxGeometry(.8,.55,.65),0xfbbf24,0,.8,0,robot);add(new THREE.SphereGeometry(.08,12,8),0x111827,-.18,.85,.34,robot);add(new THREE.SphereGeometry(.08,12,8),0x111827,.18,.85,.34,robot);const grid=new THREE.GridHelper(12,12,0x64748b,0x334155);grid.position.y=-.8;scene.add(grid);button("前進",()=>robot.translateZ(-.4));button("後退",()=>robot.translateZ(.4));button("左轉",()=>robot.rotation.y+=Math.PI/2);button("右轉",()=>robot.rotation.y-=Math.PI/2);button("重設",()=>{robot.position.set(0,0,0);robot.rotation.set(0,0,0)});

完整 HTML 程式碼(可直接另存為 06_機器人.html)

以下包含完整 HTML、CSS 與 JavaScript,不需再另外補上共用程式。請複製程式碼至獨立的 .html 檔案執行。

<!doctype html>
<html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Three.js 六個趣味入門實作</title>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.js"}}</script>
<style>body{margin:0;font-family:system-ui,'Noto Sans TC',sans-serif;background:#101b30;color:#edf5ff}#app{height:75vh}#panel{padding:16px;background:#172b46}button,input{margin:5px;padding:8px}button{cursor:pointer}label{display:inline-block;margin:8px}</style></head><body><div id="panel"><strong>Three.js 互動實作</strong><span id="controls"></span></div><div id="app"></div>
<script type="module">
import * as THREE from 'three';
const host=document.querySelector('#app'), ui=document.querySelector('#controls');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x101b30);
const camera=new THREE.PerspectiveCamera(55,innerWidth/innerHeight,.1,100);camera.position.set(0,3,8);camera.lookAt(0,0,0);
const renderer=new THREE.WebGLRenderer({antialias:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff,0x263648,2));const sun=new THREE.DirectionalLight(0xffffff,2);sun.position.set(3,6,4);scene.add(sun);
const mat=(color)=>new THREE.MeshStandardMaterial({color,roughness:.45});
const add=(geo,color,x=0,y=0,z=0,parent=scene)=>{const m=new THREE.Mesh(geo,mat(color));m.position.set(x,y,z);parent.add(m);return m};
const button=(name,fn)=>{const b=document.createElement('button');b.textContent=name;b.onclick=fn;ui.appendChild(b)};
const slider=(name,min,max,val,fn)=>{const l=document.createElement('label');l.textContent=name+' ';const e=document.createElement('input');e.type='range';e.min=min;e.max=max;e.value=val;e.oninput=()=>fn(+e.value);l.appendChild(e);ui.appendChild(l)};
let update=()=>{};
const robot=new THREE.Group();scene.add(robot);add(new THREE.BoxGeometry(1,1,.7),0x38bdf8,0,0,0,robot);add(new THREE.BoxGeometry(.8,.55,.65),0xfbbf24,0,.8,0,robot);add(new THREE.SphereGeometry(.08,12,8),0x111827,-.18,.85,.34,robot);add(new THREE.SphereGeometry(.08,12,8),0x111827,.18,.85,.34,robot);const grid=new THREE.GridHelper(12,12,0x64748b,0x334155);grid.position.y=-.8;scene.add(grid);button("前進",()=>robot.translateZ(-.4));button("後退",()=>robot.translateZ(.4));button("左轉",()=>robot.rotation.y+=Math.PI/2);button("右轉",()=>robot.rotation.y-=Math.PI/2);button("重設",()=>{robot.position.set(0,0,0);robot.rotation.set(0,0,0)});
const clock=new THREE.Clock();function animate(){const dt=Math.min(clock.getDelta(),.05);update(dt);renderer.render(scene,camera)}renderer.setAnimationLoop(animate);
function resize(){const w=host.clientWidth,h=host.clientHeight;camera.aspect=w/h;camera.updateProjectionMatrix();renderer.setSize(w,h)}addEventListener('resize',resize);resize();
</script></body></html>

動手改:加入障礙物或限制機器人不可超出地圖範圍。

獨立檔案:06_機器人.html。可部署至支援靜態網站的空間後,再使用 iframe 嵌入 Blogger。

四、六個範例比較

範例核心概念延伸 MQTT 控制
第一個 3D 立方體建立 Mesh 並透過動畫迴圈旋轉旋轉速度
幾何積木遊樂場認識 BoxGeometry、SphereGeometry 與 ConeGeometry物件切換
智慧燈光控制用按鈕與滑桿調整 DirectionalLight燈光開關
智慧風車使用 Group 組合物件並調整旋轉速度風車速度
智慧養殖魚池以水溫模擬魚群游動速度(非真實生理模型)感測值視覺化
3D 小機器人用方向鍵與按鈕移動機器人遠端方向命令

五、如何延伸到 MQTT 與 Pico 2 W?

現在的控制流程是「按鈕/滑桿 → JavaScript → Three.js」。下一階段可改為「手機 IoT MQTT Panel → MQTT Broker → MQTT.js → Three.js」,再讓 Raspberry Pi Pico 2 W 訂閱相同 Topic 控制 LED 或回報感測值。瀏覽器使用 MQTT over WebSocket,Pico 2 W 可透過 MicroPython 使用 MQTT over TCP;兩者需連線到同一個 Broker。

// 接收到 MQTT 訊息後,更新網頁狀態的概念
client.on('message', (topic, payload) => {
  if (topic === 'class/demo/windmill/speed') {
    const value = Number(payload.toString());
    if (Number.isFinite(value) && value >= 0 && value <= 10) {
      speed = value;
    }
  }
});

這段是後續 MQTT.js 整合示意,不是六個範例已內建的連線功能。

六、課堂挑戰與成果評量

學生選擇一個範例,完成「功能修改 → 操作截圖 → 程式說明 → 測試紀錄」。進階組可加入按鈕、滑桿或自訂資料,再挑戰 MQTT 虛實同步。建議成果包括 HTML 原始碼、30 秒操作影片及一段說明:改動了哪個變數、畫面產生什麼變化。

參考資源

Three.js 官方:Creating a Scene;Three.js 官方:Installation;IoT MQTT Panel 控制 Three.js。

提醒:Blogger 可能過濾 script 或 importmap 標籤,建議將互動 HTML 另行託管,部落格保留教學內容、程式碼及作品連結。本文 CSS 限定於 .threeblog 範圍。

從 Three.js 網頁動畫到 MQTT 物聯網控制:手機、網頁與 Raspberry Pi Pico 2 W 的虛實整合實作

網際網路應用Three.jsMQTTRaspberry Pi Pico 2 W

從 Three.js 網頁動畫到 MQTT 物聯網控制:手機、網頁與 Raspberry Pi Pico 2 W 的虛實整合實作

手機按下一個按鈕,網頁中的 3D 立方體改變光線,同時 Raspberry Pi Pico 2 W 的 LED 也跟著亮起。這不是手機直接連到網頁或開發板,而是三個不同的程式透過 MQTT Broker 交換訊息。本篇從可操作的最小範例出發,帶你完成虛擬與實體同步控制。

學習成果:理解 Three.js 3D 渲染、MQTT Publish/Subscribe、Topic、Payload、WebSocket、Wi-Fi 與 MicroPython,並能逐層診斷連線問題。

一、從原有的動畫與燈光控制案例出發

台灣工藝創客青創基地曾展示「物聯網燈光控制」與「物聯網動作控制」;相關教學則示範以 IoT MQTT Panel APP 發送 MQTT 命令,控制 Three.js 場景中的燈光與人物動畫。原有動畫案例的命令 Topic 為 AnimationCommand,例如 Idle、Walking、Running、Dance、Jump;燈光案例的發布 Topic 為 LightControlinHTML,命令包含 toggleHemisphereLight 與 toggleDirectionalLight。

為了讓初學者可以從零實作,本文另外設計一組更簡單的教學 Topic,並以旋轉立方體取代需載入模型的角色動畫。本文程式是重新編寫的教學範例,並非原展示網站的原始碼。

原案例:MQTT 動作控制展示、IoT MQTT Panel 控制 Three.js。

二、系統架構:誰發布?誰訂閱?

手機 IoT MQTT Panel ── Publish ──┐
                                  ▼
                             MQTT Broker
                                  │
                   ┌──────────────┴─────────────┐
                   ▼                            ▼
            網頁 MQTT.js                  Raspberry Pi Pico 2 W MicroPython
                   │                            │
                   ▼                            ▼
             Three.js 動畫                   實體 LED

        網頁與 Raspberry Pi Pico 2 W 都訂閱相同的燈光 Topic

手機是 Publisher;Broker 是訊息轉送站;網頁與 Raspberry Pi Pico 2 W 都是 Subscriber。網頁使用 MQTT over WebSocket,Raspberry Pi Pico 2 W 使用 MQTT over TCP。兩種連線方式可以接到同一個 Broker,並交換相同 Topic 的訊息。

技術角色要理解的觀念
Three.js建立 3D 場景Scene、Camera、Renderer、Mesh、Light
JavaScript處理動畫與命令事件、狀態、條件判斷
MQTT.js網頁 MQTT ClientWebSocket、Subscribe、Message
IoT MQTT Panel手機控制端Publish、Topic、Payload
Raspberry Pi Pico 2 W + MicroPython實體控制端Wi-Fi、GPIO、MQTT TCP

三、MQTT Topic 與 Payload 設計

Topic 是訊息分類的名稱,Payload 是真正傳送的內容。Broker 只負責依照 Topic 轉送,並不知道 ON 代表要點亮 LED。

Topic(本文示範)Payload接收端動作
nfu/demo/lightON、OFF網頁燈光與 Raspberry Pi Pico 2 W LED 同步切換
nfu/demo/animationPLAY、PAUSE網頁動畫播放或暫停
nfu/demo/speed0~10調整網頁旋轉速度
nfu/demo/statusON、OFFRaspberry Pi Pico 2 W 回報 LED 設定狀態
課堂使用請修改 Topic:公開 Broker 上的 nfu/demo/... 可能與其他使用者衝突,建議改成 nfu/class01/group03/light 等各組獨立名稱,且手機、網頁、Raspberry Pi Pico 2 W 三端都要同步修改。

四、實作一:完成可控制的 Three.js 網頁

先在電腦建立 index.html。以下使用 CDN 載入 Three.js 與 MQTT.js,方便學生不安裝建置工具就能入門。請將程式存成檔案,再用 VS Code Live Server 或 python -m http.server 8000 啟動本地 HTTP 伺服器,以 http://localhost:8000 開啟;避免直接以 file:// 測試。

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Three.js MQTT 虛實控制</title>
  <style>
    body { margin:0; background:#101b2c; color:white;
           font-family:Arial,sans-serif; }
    #info { padding:12px; }
    #scene { width:100%; height:70vh; }
    button { padding:10px; margin:4px; }
  </style>
</head>
<body>
  <div id="info">
    <strong>Three.js × MQTT</strong>
    <span id="status">MQTT 連線中...</span>
    <button onclick="send('nfu/demo/light','ON')">開燈</button>
    <button onclick="send('nfu/demo/light','OFF')">關燈</button>
    <button onclick="send('nfu/demo/animation','PLAY')">播放</button>
    <button onclick="send('nfu/demo/animation','PAUSE')">暫停</button>
  </div>
  <div id="scene"></div>

  <script src="https://unpkg.com/mqtt@5.10.4/dist/mqtt.min.js"></script>
  <script type="module">
    import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.1/build/three.module.js';
    const host = document.getElementById('scene');
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x15273b);
    const camera = new THREE.PerspectiveCamera(
      65, host.clientWidth / host.clientHeight, 0.1, 100);
    camera.position.set(3, 2.5, 5);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setSize(host.clientWidth, host.clientHeight);
    host.appendChild(renderer.domElement);

    const cube = new THREE.Mesh(
      new THREE.BoxGeometry(2, 2, 2),
      new THREE.MeshStandardMaterial({color:0x39a8ed})
    );
    scene.add(cube);
    const ambient = new THREE.HemisphereLight(0xffffff,0x334455,0.5);
    scene.add(ambient);
    const light = new THREE.DirectionalLight(0xffffff,2);
    light.position.set(3,5,4);
    scene.add(light);

    let playing = true;
    let speed = 0.7; // 每秒旋轉弧度
    let previous = performance.now();
    function animate(now) {
      requestAnimationFrame(animate);
      const dt = Math.min((now - previous)/1000,0.05);
      previous = now;
      if (playing) cube.rotation.y += speed * dt;
      renderer.render(scene,camera);
    }
    requestAnimationFrame(animate);

    window.addEventListener('resize', () => {
      camera.aspect = host.clientWidth / host.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(host.clientWidth,host.clientHeight);
    });

    // 瀏覽器使用 MQTT over WebSocket
    const client = mqtt.connect(
      'wss://test.mosquitto.org:8081/mqtt',
      {clientId:'nfu_web_'+Math.random().toString(16).slice(2)}
    );
    const status = document.getElementById('status');
    client.on('connect', () => {
      status.textContent = 'MQTT 已連線';
      client.subscribe([
        'nfu/demo/light',
        'nfu/demo/animation',
        'nfu/demo/speed',
        'nfu/demo/status'
      ]);
    });
    client.on('reconnect',() => status.textContent='重新連線中');
    client.on('offline',() => status.textContent='MQTT 離線');
    client.on('error',err => console.error('MQTT:',err));

    client.on('message',(topic,bytes) => {
      const value = bytes.toString();
      console.log('收到:',topic,value);
      if (topic === 'nfu/demo/light') {
        if (value === 'ON') light.visible = true;
        if (value === 'OFF') light.visible = false;
      }
      if (topic === 'nfu/demo/animation') {
        if (value === 'PLAY') playing = true;
        if (value === 'PAUSE') playing = false;
      }
      if (topic === 'nfu/demo/speed') {
        const n = Number(value);
        if (value.trim() !== '' && Number.isFinite(n)
            && n >= 0 && n <= 10) speed = n * 0.2;
      }
      if (topic === 'nfu/demo/status') {
        console.log('Raspberry Pi Pico 2 W LED 狀態:',value);
      }
    });

    function send(topic,value) {
      if (!client.connected) {
        alert('MQTT 尚未連線'); return;
      }
      client.publish(topic,value,{qos:0,retain:false});
    }
    window.send = send;
  </script>
</body>
</html>

完成後,網頁應該能看到藍色立方體旋轉;即使手機還沒有加入,也可以先用網頁按鈕發送 MQTT 命令,並由同一個網頁訂閱後執行。

五、實作二:IoT MQTT Panel 手機控制

在手機安裝 IoT MQTT Panel,新增一組 MQTT 連線,Host 填 test.mosquitto.org,Port 填 1883,連線方式為 MQTT TCP(依 APP 版本選擇)。網頁使用 WSS 8081,兩者連接的是同一個 Broker。

面板Topic值
Switch:燈光nfu/demo/light開 ON/關 OFF
Button:播放nfu/demo/animationPLAY
Button:暫停nfu/demo/animationPAUSE
Slider:速度nfu/demo/speed0~10

手機按下「關燈」時,Broker 將 OFF 轉送到網頁;網頁執行 light.visible = false。這個過程不需要知道網頁的 IP 位址,也不需要手機直接連到電腦。

六、實作三:Raspberry Pi Pico 2 W MicroPython 控制實體 LED

準備 Raspberry Pi Pico 2 W、Micro-USB 資料傳輸線,以及安裝 Thonny 的電腦。Pico 2 W 具備 Wi-Fi 功能,本實作直接使用板載 LED,因此不需要另外接線。Pico 2 W 的板載 LED 由無線晶片控制,MicroPython 可透過 Pin("LED", Pin.OUT) 存取;不要直接假設它位於 GPIO 2 或 GP25。

環境準備:先在 Thonny 選擇 MicroPython (Raspberry Pi Pico) 直譯器,安裝適用於 Pico 2 W 的 MicroPython 韌體。若出現 ImportError: no module named 'umqtt',可使用 Thonny 的「工具 → 管理套件」安裝 micropython-umqtt.simple,或將相容的 umqtt/simple.py 放入開發板。請確認使用 2.4 GHz Wi-Fi。

先在 Thonny 測試板載 LED 是否正常:

from machine import Pin
from time import sleep

led = Pin("LED", Pin.OUT)
for i in range(3):
    led.on()
    sleep(0.5)
    led.off()
    sleep(0.5)

確認燈號正常後,再建立 main.py,修改 Wi-Fi 帳號密碼並執行以下 MQTT 訂閱程式:

import network
import time
from machine import Pin, unique_id
from ubinascii import hexlify
from umqtt.simple import MQTTClient

SSID = "YOUR_WIFI"
PASSWORD = "YOUR_PASSWORD"
BROKER = "test.mosquitto.org"
TOPIC_LIGHT = b"nfu/demo/light"
TOPIC_STATUS = b"nfu/demo/status"

# Pico 2 W 板載 LED(由無線晶片控制)
led = Pin("LED", Pin.OUT)
led.off()

wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)

start = time.ticks_ms()
while not wifi.isconnected():
    if time.ticks_diff(time.ticks_ms(), start) > 20000:
        raise RuntimeError("Wi-Fi 連線逾時")
    time.sleep(0.2)
print("Wi-Fi IP:", wifi.ifconfig()[0])

client_id = b"nfu_pico2w_" + hexlify(unique_id())
client = MQTTClient(client_id, BROKER, port=1883, keepalive=60)

def on_message(topic, msg):
    if topic != TOPIC_LIGHT:
        return
    if msg == b"ON":
        led.on()
    elif msg == b"OFF":
        led.off()
    else:
        return
    state = b"ON" if led.value() else b"OFF"
    print("Pico 2 W LED:", state)
    client.publish(TOPIC_STATUS, state)

client.set_callback(on_message)
client.connect()
client.subscribe(TOPIC_LIGHT)
print("MQTT 訂閱成功")

try:
    while True:
        client.check_msg()
        time.sleep(0.1)
finally:
    client.disconnect()

當手機發布 ON 到 nfu/demo/light 時,網頁的方向光與 Pico 2 W 的板載 LED 會各自接收同一 Topic 的命令。Pico 2 W 也會發布 nfu/demo/status 回報程式設定的 LED 狀態。這不等同以光感測器確認 LED 實際發光。

教學注意:公開 Broker 的 1883 埠為未加密 MQTT TCP,僅供非敏感資料的短時間測試。正式場域請改用具有身分驗證、TLS 及 Topic 權限控管的 Broker。此範例尚未包含 Wi-Fi 與 MQTT 自動重連,適合課堂入門實驗。

七、如何驗證虛實同步?

  1. 先啟動網頁,確認看到立方體與「MQTT 已連線」。
  2. 啟動 Raspberry Pi Pico 2 W,確認 Thonny 顯示 Wi-Fi IP 與「MQTT 訂閱成功」。
  3. 手機 IoT MQTT Panel 連接同一 Broker。
  4. 手機發送 ON:網頁方向光開啟,Raspberry Pi Pico 2 W LED 點亮。
  5. 手機發送 OFF:網頁方向光關閉,Raspberry Pi Pico 2 W LED 熄滅。
  6. 發送 PAUSE、PLAY 與速度數值,觀察網頁旋轉變化。
  7. 打開瀏覽器開發者工具 Console,檢查收到的 Topic 與 Payload。
重要觀察:網頁與 Raspberry Pi Pico 2 W 各自接收同一則命令,這是「共同接收命令」,不保證兩者在毫秒等級完全同步。若需要確認實體裝置已完成動作,應再設計狀態回報與確認機制。

八、進階知識:QoS、Retain、LWT

MQTT 功能意義本專題的用途
QoS 0最多傳送一次適合入門測試與頻繁速度更新
QoS 1至少傳送一次,可能重複需處理重複命令的控制情境
QoS 2MQTT 協定層級恰好一次較嚴格的訊息傳遞需求
Retain保留 Topic 最新一則保留訊息新連線網頁取得最新設定
LWT異常斷線時 Broker 代發訊息監測 Raspberry Pi Pico 2 W 是否意外離線

特別注意:TOGGLE 命令若重複執行,可能讓燈光開了又關;ON 與 OFF 是明確設定狀態,通常較容易設計成可重複執行的命令。QoS 保證的是 MQTT 訊息傳遞語意,不保證實體硬體已完成動作。

九、常見問題與分層除錯

現象可能原因檢查方式
網頁空白Three.js 載入失敗、JavaScript 錯誤按 F12 看 Console,確認使用 ES module
網頁顯示 MQTT 離線WebSocket、TLS、網路或 Broker 問題檢查 WSS URL 與瀏覽器 Network
手機有發布但網頁不動Topic 或 Payload 不一致檢查大小寫、空白與訂閱名稱
Raspberry Pi Pico 2 W 無法連 Wi-FiSSID、密碼、頻段或訊號問題先確認 IP 與網際網路連線
Raspberry Pi Pico 2 W 找不到 umqtt套件未安裝確認 MicroPython 套件
網頁有反應,LED 沒反應GPIO 腳位、接線、電位或 Raspberry Pi Pico 2 W MQTT 問題先用簡單 LED 閃爍程式測試硬體

十、從網頁動畫延伸到智慧生活 Capstone

專題 A|智慧養殖數位分身

Raspberry Pi Pico 2 W 發布水溫或溶氧感測值,Three.js 以水色、警示與魚群動畫顯示水質變化。進一步加入 Django 儲存歷史資料。

專題 B|水井三寶智慧互動展覽

將白馬、烏龜、姻緣花轉譯為 3D 或 2D 互動場景,手機發布命令,Raspberry Pi Pico 2 W 同步控制 WS2812B 燈光與語音模組,連結地方文化與網路技術。

專題 C|兒童機器人虛實互動

網頁模擬機器人前進、左轉、右轉,透過 MQTT 發送控制命令到實體機器人;學生需自行設計安全停止與狀態回報機制。

十一、六小時教學安排

階段時間操作任務成果證據
1. 網頁動畫2 小時建立 Three.js 場景、燈光、旋轉動畫可操作的 3D 網頁
2. MQTT 通訊2 小時手機發布、網頁訂閱與 Console 診斷手機控制網頁影片或截圖
3. 虛實整合2 小時Raspberry Pi Pico 2 W 訂閱、LED 控制、狀態回報虛實同步展示及系統架構圖

學生挑戰題

  1. 為什麼瀏覽器使用 WSS,而 Raspberry Pi Pico 2 W 可以使用 MQTT TCP?
  2. 如果兩個學生使用相同 Topic,可能發生什麼事?
  3. 如何設計狀態回報,分辨「命令已發布」與「LED 已設定」?
  4. 如何把立方體換成 3D 人物,讓 Walking 與 Dance 對應不同動畫片段?
  5. 如果 Broker 暫時斷線,網頁與 Raspberry Pi Pico 2 W 應該如何恢復?

十二、結語:看得懂、連得上、做得出來

從 Three.js 的虛擬動畫,到手機 IoT MQTT Panel 發布命令,再到 Raspberry Pi Pico 2 W 控制實體 LED,學生實際經歷了一則訊息如何穿越不同裝置與軟體環境。這正是網際網路應用的核心:不只是會寫網頁,更能說明訊息如何傳遞、如何驗證、如何安全且可靠地讓系統運作。

未來加入 Django、資料庫、感測器與 AI 模型,就可以將這個小型實驗擴充為智慧養殖、地方文化互動展示或智慧教育系統。

延伸閱讀與技術參考

教學說明:本文的 Topic、程式及系統架構為重新設計的入門教材;公開測試 Broker 僅適合非敏感資料實驗。正式場域部署需加入 TLS、帳號驗證、Topic ACL、重連與設備安全機制。

從 Three.js 網頁動畫到 MQTT 物聯網控制:手機、網頁與 ESP32 的虛實整合實作

網際網路應用Three.jsMQTTESP32

從 Three.js 網頁動畫到 MQTT 物聯網控制:手機、網頁與 ESP32 的虛實整合實作

手機按下一個按鈕,網頁中的 3D 立方體改變光線,同時 ESP32 的 LED 也跟著亮起。這不是手機直接連到網頁或開發板,而是三個不同的程式透過 MQTT Broker 交換訊息。本篇從可操作的最小範例出發,帶你完成虛擬與實體同步控制。

學習成果:理解 Three.js 3D 渲染、MQTT Publish/Subscribe、Topic、Payload、WebSocket、Wi-Fi 與 MicroPython,並能逐層診斷連線問題。

一、從原有的動畫與燈光控制案例出發

台灣工藝創客青創基地曾展示「物聯網燈光控制」與「物聯網動作控制」;相關教學則示範以 IoT MQTT Panel APP 發送 MQTT 命令,控制 Three.js 場景中的燈光與人物動畫。原有動畫案例的命令 Topic 為 AnimationCommand,例如 Idle、Walking、Running、Dance、Jump;燈光案例的發布 Topic 為 LightControlinHTML,命令包含 toggleHemisphereLight 與 toggleDirectionalLight。

為了讓初學者可以從零實作,本文另外設計一組更簡單的教學 Topic,並以旋轉立方體取代需載入模型的角色動畫。本文程式是重新編寫的教學範例,並非原展示網站的原始碼。

原案例:MQTT 動作控制展示、IoT MQTT Panel 控制 Three.js。

二、系統架構:誰發布?誰訂閱?

手機 IoT MQTT Panel ── Publish ──┐
                                  ▼
                             MQTT Broker
                                  │
                   ┌──────────────┴─────────────┐
                   ▼                            ▼
            網頁 MQTT.js                  ESP32 MicroPython
                   │                            │
                   ▼                            ▼
             Three.js 動畫                   實體 LED

        網頁與 ESP32 都訂閱相同的燈光 Topic

手機是 Publisher;Broker 是訊息轉送站;網頁與 ESP32 都是 Subscriber。網頁使用 MQTT over WebSocket,ESP32 使用 MQTT over TCP。兩種連線方式可以接到同一個 Broker,並交換相同 Topic 的訊息。

技術角色要理解的觀念
Three.js建立 3D 場景Scene、Camera、Renderer、Mesh、Light
JavaScript處理動畫與命令事件、狀態、條件判斷
MQTT.js網頁 MQTT ClientWebSocket、Subscribe、Message
IoT MQTT Panel手機控制端Publish、Topic、Payload
ESP32 + MicroPython實體控制端Wi-Fi、GPIO、MQTT TCP

三、MQTT Topic 與 Payload 設計

Topic 是訊息分類的名稱,Payload 是真正傳送的內容。Broker 只負責依照 Topic 轉送,並不知道 ON 代表要點亮 LED。

Topic(本文示範)Payload接收端動作
nfu/demo/lightON、OFF網頁燈光與 ESP32 LED 同步切換
nfu/demo/animationPLAY、PAUSE網頁動畫播放或暫停
nfu/demo/speed0~10調整網頁旋轉速度
nfu/demo/statusON、OFFESP32 回報 LED 設定狀態
課堂使用請修改 Topic:公開 Broker 上的 nfu/demo/... 可能與其他使用者衝突,建議改成 nfu/class01/group03/light 等各組獨立名稱,且手機、網頁、ESP32 三端都要同步修改。

四、實作一:完成可控制的 Three.js 網頁

先在電腦建立 index.html。以下使用 CDN 載入 Three.js 與 MQTT.js,方便學生不安裝建置工具就能入門。請將程式存成檔案,再用 VS Code Live Server 或 python -m http.server 8000 啟動本地 HTTP 伺服器,以 http://localhost:8000 開啟;避免直接以 file:// 測試。

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Three.js MQTT 虛實控制</title>
  <style>
    body { margin:0; background:#101b2c; color:white;
           font-family:Arial,sans-serif; }
    #info { padding:12px; }
    #scene { width:100%; height:70vh; }
    button { padding:10px; margin:4px; }
  </style>
</head>
<body>
  <div id="info">
    <strong>Three.js × MQTT</strong>
    <span id="status">MQTT 連線中...</span>
    <button onclick="send('nfu/demo/light','ON')">開燈</button>
    <button onclick="send('nfu/demo/light','OFF')">關燈</button>
    <button onclick="send('nfu/demo/animation','PLAY')">播放</button>
    <button onclick="send('nfu/demo/animation','PAUSE')">暫停</button>
  </div>
  <div id="scene"></div>

  <script src="https://unpkg.com/mqtt@5.10.4/dist/mqtt.min.js"></script>
  <script type="module">
    import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.1/build/three.module.js';
    const host = document.getElementById('scene');
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x15273b);
    const camera = new THREE.PerspectiveCamera(
      65, host.clientWidth / host.clientHeight, 0.1, 100);
    camera.position.set(3, 2.5, 5);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setSize(host.clientWidth, host.clientHeight);
    host.appendChild(renderer.domElement);

    const cube = new THREE.Mesh(
      new THREE.BoxGeometry(2, 2, 2),
      new THREE.MeshStandardMaterial({color:0x39a8ed})
    );
    scene.add(cube);
    const ambient = new THREE.HemisphereLight(0xffffff,0x334455,0.5);
    scene.add(ambient);
    const light = new THREE.DirectionalLight(0xffffff,2);
    light.position.set(3,5,4);
    scene.add(light);

    let playing = true;
    let speed = 0.7; // 每秒旋轉弧度
    let previous = performance.now();
    function animate(now) {
      requestAnimationFrame(animate);
      const dt = Math.min((now - previous)/1000,0.05);
      previous = now;
      if (playing) cube.rotation.y += speed * dt;
      renderer.render(scene,camera);
    }
    requestAnimationFrame(animate);

    window.addEventListener('resize', () => {
      camera.aspect = host.clientWidth / host.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(host.clientWidth,host.clientHeight);
    });

    // 瀏覽器使用 MQTT over WebSocket
    const client = mqtt.connect(
      'wss://test.mosquitto.org:8081/mqtt',
      {clientId:'nfu_web_'+Math.random().toString(16).slice(2)}
    );
    const status = document.getElementById('status');
    client.on('connect', () => {
      status.textContent = 'MQTT 已連線';
      client.subscribe([
        'nfu/demo/light',
        'nfu/demo/animation',
        'nfu/demo/speed',
        'nfu/demo/status'
      ]);
    });
    client.on('reconnect',() => status.textContent='重新連線中');
    client.on('offline',() => status.textContent='MQTT 離線');
    client.on('error',err => console.error('MQTT:',err));

    client.on('message',(topic,bytes) => {
      const value = bytes.toString();
      console.log('收到:',topic,value);
      if (topic === 'nfu/demo/light') {
        if (value === 'ON') light.visible = true;
        if (value === 'OFF') light.visible = false;
      }
      if (topic === 'nfu/demo/animation') {
        if (value === 'PLAY') playing = true;
        if (value === 'PAUSE') playing = false;
      }
      if (topic === 'nfu/demo/speed') {
        const n = Number(value);
        if (value.trim() !== '' && Number.isFinite(n)
            && n >= 0 && n <= 10) speed = n * 0.2;
      }
      if (topic === 'nfu/demo/status') {
        console.log('ESP32 LED 狀態:',value);
      }
    });

    function send(topic,value) {
      if (!client.connected) {
        alert('MQTT 尚未連線'); return;
      }
      client.publish(topic,value,{qos:0,retain:false});
    }
    window.send = send;
  </script>
</body>
</html>

完成後,網頁應該能看到藍色立方體旋轉;即使手機還沒有加入,也可以先用網頁按鈕發送 MQTT 命令,並由同一個網頁訂閱後執行。

五、實作二:IoT MQTT Panel 手機控制

在手機安裝 IoT MQTT Panel,新增一組 MQTT 連線,Host 填 test.mosquitto.org,Port 填 1883,連線方式為 MQTT TCP(依 APP 版本選擇)。網頁使用 WSS 8081,兩者連接的是同一個 Broker。

面板Topic值
Switch:燈光nfu/demo/light開 ON/關 OFF
Button:播放nfu/demo/animationPLAY
Button:暫停nfu/demo/animationPAUSE
Slider:速度nfu/demo/speed0~10

手機按下「關燈」時,Broker 將 OFF 轉送到網頁;網頁執行 light.visible = false。這個過程不需要知道網頁的 IP 位址,也不需要手機直接連到電腦。

六、實作三:ESP32 MicroPython 控制實體 LED

準備 ESP32 開發板、LED、約 220~330Ω 限流電阻、麵包板及 USB 傳輸線。以外接 LED 為例,GPIO 2 經電阻接 LED 正極,LED 負極接 GND。若板子已有內建 LED,請依板型確認腳位與高低電位邏輯。

在 Thonny 建立 main.py,修改 Wi-Fi 帳號與密碼後上傳。此例使用 umqtt.simple,部分 MicroPython 韌體需要另外安裝 micropython-umqtt.simple。

import network
import time
from machine import Pin
from umqtt.simple import MQTTClient

SSID = "YOUR_WIFI"
PASSWORD = "YOUR_PASSWORD"
BROKER = "test.mosquitto.org"
TOPIC_LIGHT = b"nfu/demo/light"
TOPIC_STATUS = b"nfu/demo/status"

led = Pin(2, Pin.OUT)
led.value(0)

wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)

start = time.ticks_ms()
while not wifi.isconnected():
    if time.ticks_diff(time.ticks_ms(),start) > 15000:
        raise RuntimeError("Wi-Fi 連線逾時")
    time.sleep(0.2)
print("Wi-Fi IP:",wifi.ifconfig()[0])

client = MQTTClient(
    b"nfu_esp32_" + str(time.ticks_ms()).encode(),
    BROKER,
    port=1883,
    keepalive=60
)

def on_message(topic,msg):
    if topic != TOPIC_LIGHT:
        return
    if msg == b"ON":
        led.value(1)
    elif msg == b"OFF":
        led.value(0)
    else:
        return
    state = b"ON" if led.value() else b"OFF"
    print("LED:",state)
    client.publish(TOPIC_STATUS,state)

client.set_callback(on_message)
client.connect()
client.subscribe(TOPIC_LIGHT)
print("MQTT 訂閱成功")

try:
    while True:
        client.check_msg()
        time.sleep(0.1)
finally:
    client.disconnect()

ESP32 收到 ON 後點亮 LED,並向 nfu/demo/status 回報狀態。這裡的狀態是程式對輸出腳位的設定結果,並非透過光感測器確認 LED 真的發光。這份程式適合課堂短時間實驗;長時間運作仍需增加 Wi-Fi/MQTT 斷線重連及錯誤處理。

七、如何驗證虛實同步?

  1. 先啟動網頁,確認看到立方體與「MQTT 已連線」。
  2. 啟動 ESP32,確認 Thonny 顯示 Wi-Fi IP 與「MQTT 訂閱成功」。
  3. 手機 IoT MQTT Panel 連接同一 Broker。
  4. 手機發送 ON:網頁方向光開啟,ESP32 LED 點亮。
  5. 手機發送 OFF:網頁方向光關閉,ESP32 LED 熄滅。
  6. 發送 PAUSE、PLAY 與速度數值,觀察網頁旋轉變化。
  7. 打開瀏覽器開發者工具 Console,檢查收到的 Topic 與 Payload。
重要觀察:網頁與 ESP32 各自接收同一則命令,這是「共同接收命令」,不保證兩者在毫秒等級完全同步。若需要確認實體裝置已完成動作,應再設計狀態回報與確認機制。

八、進階知識:QoS、Retain、LWT

MQTT 功能意義本專題的用途
QoS 0最多傳送一次適合入門測試與頻繁速度更新
QoS 1至少傳送一次,可能重複需處理重複命令的控制情境
QoS 2MQTT 協定層級恰好一次較嚴格的訊息傳遞需求
Retain保留 Topic 最新一則保留訊息新連線網頁取得最新設定
LWT異常斷線時 Broker 代發訊息監測 ESP32 是否意外離線

特別注意:TOGGLE 命令若重複執行,可能讓燈光開了又關;ON 與 OFF 是明確設定狀態,通常較容易設計成可重複執行的命令。QoS 保證的是 MQTT 訊息傳遞語意,不保證實體硬體已完成動作。

九、常見問題與分層除錯

現象可能原因檢查方式
網頁空白Three.js 載入失敗、JavaScript 錯誤按 F12 看 Console,確認使用 ES module
網頁顯示 MQTT 離線WebSocket、TLS、網路或 Broker 問題檢查 WSS URL 與瀏覽器 Network
手機有發布但網頁不動Topic 或 Payload 不一致檢查大小寫、空白與訂閱名稱
ESP32 無法連 Wi-FiSSID、密碼、頻段或訊號問題先確認 IP 與網際網路連線
ESP32 找不到 umqtt套件未安裝確認 MicroPython 套件
網頁有反應,LED 沒反應GPIO 腳位、接線、電位或 ESP32 MQTT 問題先用簡單 LED 閃爍程式測試硬體

十、從網頁動畫延伸到智慧生活 Capstone

專題 A|智慧養殖數位分身

ESP32 發布水溫或溶氧感測值,Three.js 以水色、警示與魚群動畫顯示水質變化。進一步加入 Django 儲存歷史資料。

專題 B|水井三寶智慧互動展覽

將白馬、烏龜、姻緣花轉譯為 3D 或 2D 互動場景,手機發布命令,ESP32 同步控制 WS2812B 燈光與語音模組,連結地方文化與網路技術。

專題 C|兒童機器人虛實互動

網頁模擬機器人前進、左轉、右轉,透過 MQTT 發送控制命令到實體機器人;學生需自行設計安全停止與狀態回報機制。

十一、六小時教學安排

階段時間操作任務成果證據
1. 網頁動畫2 小時建立 Three.js 場景、燈光、旋轉動畫可操作的 3D 網頁
2. MQTT 通訊2 小時手機發布、網頁訂閱與 Console 診斷手機控制網頁影片或截圖
3. 虛實整合2 小時ESP32 訂閱、LED 控制、狀態回報虛實同步展示及系統架構圖

學生挑戰題

  1. 為什麼瀏覽器使用 WSS,而 ESP32 可以使用 MQTT TCP?
  2. 如果兩個學生使用相同 Topic,可能發生什麼事?
  3. 如何設計狀態回報,分辨「命令已發布」與「LED 已設定」?
  4. 如何把立方體換成 3D 人物,讓 Walking 與 Dance 對應不同動畫片段?
  5. 如果 Broker 暫時斷線,網頁與 ESP32 應該如何恢復?

十二、結語:看得懂、連得上、做得出來

從 Three.js 的虛擬動畫,到手機 IoT MQTT Panel 發布命令,再到 ESP32 控制實體 LED,學生實際經歷了一則訊息如何穿越不同裝置與軟體環境。這正是網際網路應用的核心:不只是會寫網頁,更能說明訊息如何傳遞、如何驗證、如何安全且可靠地讓系統運作。

未來加入 Django、資料庫、感測器與 AI 模型,就可以將這個小型實驗擴充為智慧養殖、地方文化互動展示或智慧教育系統。

延伸閱讀與技術參考

教學說明:本文的 Topic、程式及系統架構為重新設計的入門教材;公開測試 Broker 僅適合非敏感資料實驗。正式場域部署需加入 TLS、帳號驗證、Topic ACL、重連與設備安全機制。

2026年11月16日 星期一

Python 正規表示式(Regular Expression): 從生活中的文字遊戲學會 Regex

Python 正規表示式(Regular Expression): 從生活中的文字遊戲學會 Regex

Python 程式實習|文字處理與智慧生活應用


圖:Python 正規表示式(Regex)教學總覽, 透過生活化文字搜尋、格式檢查與資料擷取, 認識正規表示式的實際應用。

你是否曾經想過:

  • 如何從一篇文章中找出所有手機號碼?
  • 如何快速檢查密碼是否符合格式?
  • 如何從聊天訊息中找出 Emoji?
  • 如何從飲料訂單中取得飲料名稱與數量?
  • 如何從智慧養殖訊息中擷取水溫、pH 與溶氧?

這些看起來不同的問題, 其實都可以利用 Python 的 正規表示式(Regular Expression,簡稱 Regex) 來處理。

正規表示式就像一把「文字搜尋放大鏡」, 只要設定好規則, Python 就能快速找出符合條件的文字。

本篇文章將從有趣的生活案例開始, 一步一步認識 Regex, 最後延伸到智慧生活與 Python 專題應用。

一、什麼是正規表示式?

正規表示式是一種描述文字模式的工具。

一般文字搜尋通常只能找出固定的文字, 例如搜尋「Python」。

但是,如果想找出文章中的所有數字, 或所有符合格式的手機號碼, 就需要更有彈性的搜尋方式。

例如:

\d+

這個 Regex 表示: 尋找一個或多個連續數字。

其中:

  • \d:代表一個數字。
  • +:代表前面的模式出現一次或多次。

因此,Regex 不只是尋找固定文字, 而是根據規則尋找符合條件的資料。

二、Python 如何使用正規表示式?

Python 內建 re 模組, 不需要另外安裝套件。

先看一個簡單範例。

import re

text = "今天買了3杯奶茶和2份雞排"

result = re.findall(r"\d+", text)

print(result)

執行結果:

['3', '2']

這裡使用:

  • import re:載入正規表示式模組。
  • re.findall():找出所有符合規則的內容。
  • r"\d+":表示尋找連續數字。

字串前面的 r 代表原始字串(Raw String), 可以讓反斜線在 Regex 中更容易正確使用。

三、常用 Regex 符號總整理

符號 意義 範例
. 任意單一字元(預設不含換行) a.c
^ 字串開頭 ^09
$ 字串結尾 \d+$
* 重複零次或多次 ab*
+ 重複一次或多次 \d+
? 重複零次或一次 colou?r
{n} 重複 n 次 \d{4}
[] 字元集合 [ABC]
() 擷取群組 (\d{3})
| 或 貓|狗
\d 數字 \d{4}
\w Unicode 文字字元或底線 \w+
\s 空白字元 \s+
學習建議:

不需要一次記住所有符號。 先學會 \d、 +、[]、 () 與 {n}, 就可以完成許多實用的文字搜尋任務。

四、實驗一:文字尋寶,找出所有數字

假設一段購物訊息包含數量與金額:

import re

message = "今天買了3杯奶茶、2份雞排,總共185元"

numbers = re.findall(r"\d+", message)

print(numbers)

執行結果:

['3', '2', '185']

Python 可以快速找出文字中的數字, 不需要逐一檢查每個字元。

進階挑戰:如何找出小數?

import re

text = "水溫28.5度,溶氧6.8mg/L"

numbers = re.findall(
    r"\d+(?:\.\d+)?",
    text
)

print(numbers)

執行結果:

['28.5', '6.8']

其中 (?:\.\d+)? 表示可以選擇性地包含小數點與後續數字。

五、實驗二:手機號碼偵探

利用 Regex 檢查手機號碼是否符合指定格式。

import re

phones = [
    "0912-345-678",
    "0912345678",
    "0912-34-567",
    "0812-345-678"
]

pattern = r"09\d{2}-?\d{3}-?\d{3}"

for phone in phones:
    if re.fullmatch(pattern, phone):
        print(phone, "格式正確")
    else:
        print(phone, "格式錯誤")

執行結果:

0912-345-678 格式正確
0912345678 格式正確
0912-34-567 格式錯誤
0812-345-678 格式錯誤

re.fullmatch() 要求整個字串都符合規則, 很適合用於輸入格式檢查。

這裡只是檢查格式, 不代表號碼實際存在或可以使用。

六、實驗三:Emoji 尋寶遊戲

現在的文字訊息經常包含 Emoji。 Python 可以透過 Unicode 範圍, 搜尋部分常見的表情符號。

import re

text = "今天寫Python好開心😄!專題完成🎉,加油💪"

pattern = r"[\U0001F300-\U0001FAFF]"

emojis = re.findall(pattern, text)

print(emojis)

執行結果:

['😄', '🎉', '💪']

這個範例示範如何使用 Unicode 範圍進行搜尋。

注意:

這個簡易模式只能找到指定範圍內的部分 Emoji。 有些 Emoji 是由多個 Unicode 碼位組成, 例如 👩‍💻, 因此不能保證完整辨識所有 Emoji。

七、實驗四:密碼守門員

假設我們希望密碼符合以下規則:

  • 至少八個字元。
  • 必須包含英文字母。
  • 必須包含數字。
  • 只允許英文字母與數字。
import re

passwords = [
    "python",
    "python123",
    "12345678",
    "Hello2026"
]

pattern = (
    r"(?=.*[A-Za-z])"
    r"(?=.*\d)"
    r"[A-Za-z\d]{8,}"
)

for password in passwords:
    ok = re.fullmatch(pattern, password)

    if ok:
        print(password, "符合規則")
    else:
        print(password, "不符合規則")

執行結果:

python 不符合規則
python123 符合規則
12345678 不符合規則
Hello2026 符合規則

其中:

  • (?=.*[A-Za-z]):至少包含一個英文字母。
  • (?=.*\d):至少包含一個數字。
  • [A-Za-z\d]{8,}:至少八個英文字母或數字。

這是格式檢查練習, 符合規則並不代表密碼一定安全。 實際系統還需要考慮常見密碼與外洩密碼等風險。

八、實驗五:飲料店 POS 訂單解析

假設飲料店收到一段訂單文字:

珍珠奶茶3杯、紅茶2杯、綠茶5杯

我們希望 Python 自動找出飲料名稱與數量。

import re

order = "珍珠奶茶3杯、紅茶2杯、綠茶5杯"

pattern = r"([\u4e00-\u9fff]+)(\d+)杯"

items = re.findall(pattern, order)

for name, quantity in items:
    print(f"{name}:{quantity}杯")

執行結果:

珍珠奶茶:3杯
紅茶:2杯
綠茶:5杯

這裡使用兩個擷取群組:

  • 第一個群組取得飲料名稱。
  • 第二個群組取得數量。

延伸:加入價格計算

prices = {
    "珍珠奶茶": 50,
    "紅茶": 25,
    "綠茶": 30
}

total = 0

for name, quantity in items:
    subtotal = prices[name] * int(quantity)
    total += subtotal

    print(name, subtotal, "元")

print("總金額:", total, "元")

執行結果:

珍珠奶茶 150 元
紅茶 50 元
綠茶 150 元
總金額: 350 元

這個範例結合 Regex、字典、 迴圈與數值運算, 已經具備簡易 POS 系統的基本概念。

九、實驗六:智慧養殖水質資料解析

在智慧養殖或 IoT 應用中, 設備可能傳送文字形式的監測資料。

例如:

第一池 水溫:28.5 pH:7.6 溶氧:6.8

我們可以利用 Regex 擷取數值。

import re

message = "第一池 水溫:28.5 pH:7.6 溶氧:6.8"

pattern = (
    r"水溫:(\d+(?:\.\d+)?)\s+"
    r"pH:(\d+(?:\.\d+)?)\s+"
    r"溶氧:(\d+(?:\.\d+)?)"
)

match = re.search(pattern, message)

if match:
    temperature, ph, oxygen = map(
        float,
        match.groups()
    )

    print("水溫:", temperature)
    print("pH:", ph)
    print("溶氧:", oxygen)
else:
    print("資料格式不正確")

執行結果:

水溫: 28.5
pH: 7.6
溶氧: 6.8

這個範例可延伸到:

  • CSV 水質資料儲存。
  • SQLite 歷史紀錄查詢。
  • Matplotlib 水質趨勢圖。
  • 依模擬門檻顯示異常提醒。
  • 智慧養殖監測系統專題。

十、Python re 模組的四個重要函式

函式 主要功能
re.findall() 找出所有符合條件的內容
re.search() 搜尋第一個符合條件的位置
re.fullmatch() 檢查整個字串是否符合格式
re.sub() 將符合條件的文字替換

補充:自動整理多餘空白

import re

text = "Python    是   很有趣的   程式語言"

clean = re.sub(r"\s+", " ", text)

print(clean)

執行結果:

Python 是 很有趣的 程式語言

這個技巧很適合用於資料清理。

十一、課堂挑戰:Regex 文字偵探

挑戰一:車牌搜尋

從文字中找出類似 ABC-1234 的車牌格式。

提示: [A-Z]{3}-\d{4}

挑戰二:電子郵件搜尋

從一段文章中找出電子郵件地址。

提示: [\w.+-]+@[\w.-]+\.[A-Za-z]{2,}

這只是常見格式的簡化搜尋規則, 不是完整的電子郵件有效性驗證。

挑戰三:日期搜尋

從文章中找出:

2026/11/12
2026-11-12

提示: \d{4}[/-]\d{2}[/-]\d{2}

注意:這只能檢查基本格式, 無法判斷日期是否真實存在。

挑戰四:智慧農業關鍵字搜尋

找出文章中的: 農業、養殖、水質、溶氧。

提示: 農業|養殖|水質|溶氧

十二、Regex 可以如何應用在 Capstone 專題?

在 Python 智慧生活微型 Capstone 專題中, Regex 可以作為實用的功能模組。

專題類型 Regex 應用
智慧商店 訂單文字解析、商品與數量擷取
智慧養殖 感測訊息解析、監測數值擷取
智慧教育 答案格式檢查、文字練習
地方文化 故事關鍵字搜尋、文字資料整理
智慧生活 手機格式檢查、資料清理
使用提醒:

Regex 適合處理具有規律的文字格式。 如果資料本身已經是 CSV、JSON 或完整 HTML, 應優先使用 Python 對應的解析工具, 不要全部依賴正規表示式。

十三、學習自我檢核

  • □ 我知道 Regex 的基本用途。
  • □ 我能使用 re.findall() 搜尋文字。
  • □ 我知道 \d、+ 與 {n} 的意義。
  • □ 我能使用 re.fullmatch() 檢查格式。
  • □ 我能使用擷取群組取得資料。
  • □ 我能利用 re.sub() 整理文字。
  • □ 我能提出一個 Regex 的智慧生活應用。

十四、結語:讓 Python 成為文字偵探

正規表示式看起來像是一串難懂的符號, 但只要從生活中的文字問題開始, 就會發現它非常實用。

從尋找數字、檢查手機號碼、 辨識 Emoji、解析飲料訂單, 到智慧養殖監測資料處理, Regex 都可以發揮作用。

對 Python 初學者而言, 不需要一次記住所有語法, 而是應該透過實際問題, 逐步理解不同規則的用途。

學習 Regex 的最好方法, 不是背誦符號, 而是自己設計文字規則, 讓 Python 幫你找到答案。

當同學能將 Regex 與字典、函式、 檔案處理及資料分析結合, 就能進一步發展出更完整的智慧生活應用系統。


Python 程式實習|文字處理與智慧生活應用系列