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 範圍。