<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jacy Chu on Medium]]></title>
        <description><![CDATA[Stories by Jacy Chu on Medium]]></description>
        <link>https://medium.com/@jacychu?source=rss-1f5721ebe68b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IiQlP9tPstSKJrUhekDv1g.png</url>
            <title>Stories by Jacy Chu on Medium</title>
            <link>https://medium.com/@jacychu?source=rss-1f5721ebe68b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:10:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacychu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[從零打造 Google Sheets MCP Server]]></title>
            <link>https://jacychu.medium.com/%E5%BE%9E%E9%9B%B6%E6%89%93%E9%80%A0-google-sheets-mcp-server-4d16d6e2e6e0?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d16d6e2e6e0</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 01:40:19 GMT</pubDate>
            <atom:updated>2026-08-17T03:27:55.415Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>從 Service Account 授權、Tools 設計，到 Claude Desktop 與 Claude Code 串接的完整實作紀錄</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09Rpg6Y-ZhCycQO-qs4Zww.png" /></figure><p><strong>專案：</strong> travel-budget-mcp（旅行記帳查詢/管理工具）</p><h3>一、核心概念</h3><p>一個 MCP server 的運作邏輯：</p><pre>使用者提出問題<br>    ↓<br>Claude 判斷該呼叫哪個工具（決策者是 Claude 本身，不是 server，也不是 App）<br>    ↓<br>（若需要授權）跳出 Allow once / Always allow 確認<br>    ↓<br>Server 收到請求，執行對應邏輯（讀/寫外部資料源）<br>    ↓<br>Server 把結果包裝成文字，回傳給 Claude<br>    ↓<br>Claude 用自然語言組織回答，呈現給使用者</pre><p><strong>重要認知：</strong> 工具會不會被呼叫、呼叫哪一個，完全由 Claude 根據對話內容和工具的 description 做語意判斷，不是寫死的規則。這也是為什麼「工具描述寫得清不清楚」直接影響 Claude 願不願意主動使用它。</p><h3>二、前置作業：Google Cloud 設定</h3><p>因為 Google Sheets 是私人資料，需要透過 <strong>Service Account（服務帳號）</strong> 這種免登入流程的授權方式，取得程式操作表格的權限。步驟如下：</p><h4>步驟 1：建立 Google Cloud 專案</h4><p>前往 <a href="https://console.cloud.google.com/">console.cloud.google.com</a>，建立新專案（本次命名為 travel-budget-mcp）。</p><h4>步驟 2：啟用 Google Sheets API</h4><p>在「APIs &amp; Services」→「Library」搜尋 Google Sheets API，點擊 Enable。</p><h4>步驟 3：建立服務帳號（Service Account）</h4><p>「APIs &amp; Services」→「Credentials」→ Create Credentials → Service Account。這種方式比一般 OAuth 登入流程簡單，適合個人小工具使用，不需要每次手動登入授權。</p><h4>步驟 4：下載金鑰檔案（JSON Key）</h4><p>進入服務帳號詳細頁 →「Keys」頁籤 → Add Key → Create new key → 選 JSON 格式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEivhSa6sNmRc_iRFyUiqQ.png" /></figure><p>⚠️ <strong>安全提醒：</strong> 這個 JSON 檔案就是程式的「鑰匙」，內含私鑰，絕對不能上傳到公開的地方（例如 GitHub 公開 repo），也不能分享給任何人。專案中已加入 .gitignore 排除這類檔案。</p><h4>步驟 5：把服務帳號加入試算表共用名單</h4><p>打開 JSON 檔案，找到 client_email 欄位（格式類似 xxx@專案名稱.iam.gserviceaccount.com）。回到 Google Sheet，點「共用」，把這個 email 加入，權限設為「編輯者」。</p><p>⚠️ <strong>這一步是最容易漏掉的關卡 — 沒有這步，程式即使金鑰正確，仍然會遇到權限被拒絕的錯誤。</strong></p><h3>三、專案建置</h3><h4>步驟 1：初始化專案</h4><pre>mkdir sheets-mcp-server &amp;&amp; cd sheets-mcp-server<br>npm init -y</pre><h4>步驟 2：安裝套件</h4><pre>npm install @modelcontextprotocol/sdk googleapis</pre><ul><li>@modelcontextprotocol/sdk：官方 MCP 協定 SDK</li><li>googleapis：Google 官方提供的 API 客戶端，用來跟 Sheets API 溝通</li></ul><h4>步驟 3：設定 ES Module</h4><p>在 package.json 加入 &quot;type&quot;: &quot;module&quot;，讓專案可以使用 import/export 語法（而非舊式的 require）。</p><h3>四、程式架構設計</h3><h4>授權連線邏輯</h4><pre>async function getSheetsClient() {<br>  const credentials = JSON.parse(readFileSync(KEY_FILE, &quot;utf-8&quot;));<br>  const auth = new google.auth.GoogleAuth({<br>    credentials,<br>    scopes: [&quot;https://www.googleapis.com/auth/spreadsheets&quot;],<br>  });<br>  const authClient = await auth.getClient();<br>  return google.sheets({ version: &quot;v4&quot;, auth: authClient });<br>}</pre><p>用服務帳號的金鑰檔案，向 Google 換取一組有時效性的授權 token，之後每次呼叫 API 都用這個已授權的 client。</p><h4>四個工具（Tools）</h4><p>工具名稱 功能 涉及操作 get_trip_summary 查詢某趟旅行的花費明細與剩餘預算 讀取 add_expense 新增一筆支出到指定分頁 寫入 get_all_trips_stats 跨分頁統計所有旅行的花費、算平均 讀取（多次） update_trip_budget 修改指定旅行的預算上限＆寫入</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*42qQFvIpr4CPMeHj7-t3tw.png" /><figcaption>檔案架構</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca86600f78ede4f6a5c2517e983dfe3/href">https://medium.com/media/4ca86600f78ede4f6a5c2517e983dfe3/href</a></iframe><p>其中的 KEY_FILE “travel-budget-mcp-xxxxxxx.json” 還有SPREADSHEET_ID可以在前置作業中的步驟四有 JSON 檔案就是程式的「鑰匙」。因travel-budget-mcp-xxxxxxx.json是機敏資訊，所以這邊改用xxxx把內容蓋住。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5uC-N4-iHNOqm5-on2MWQ.png" /><figcaption>travel-budget-mcp-xxxxxxx.json</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4338c31e3344c56f7f81a818f0174c4b/href">https://medium.com/media/4338c31e3344c56f7f81a818f0174c4b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6952d0fbd364a0e02e9e40a768412c39/href">https://medium.com/media/6952d0fbd364a0e02e9e40a768412c39/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d1909920a73f1cc3afb2588ca17c407/href">https://medium.com/media/8d1909920a73f1cc3afb2588ca17c407/href</a></iframe><h3>五、測試流程（依序進行）</h3><p>延續股價 server 時建立的習慣：每寫完一個工具，就寫一支對應的小測試腳本，親自驗證整條路能不能跑通，而不是等全部寫完才一次測試。</p><ol><li>node --check index.js——先確認語法正確</li><li>test-trip-summary.js——測試查詢功能 ✅ 一次成功，明細數字與試算表完全吻合</li><li>test-add-expense.js——測試新增支出 ✅ 成功寫入，並用測試資料（金額 100、備註「請刪除」）方便驗證後清除</li><li>test-all-stats.js——測試跨分頁統計 ⚠️ 發現問題（見下一節）</li><li>接上 Claude Desktop 後，直接在對話中測試自然語言呼叫</li></ol><h3>六、遇到的問題與解法</h3><h4>問題一：跨分頁統計時，部分旅行的金額算錯</h4><p><strong>現象：</strong> 「巴黎」統計出「總花費：5」，「蜜月」也顯示出不合理的數字，其他分頁（福岡、東京等）都正確。</p><p>排查過程： 原本程式邏輯是寫死抓 D 欄當作「計算金額」：</p><pre>range: `${sheetName}!D2:D50`  // 有問題的寫法</pre><p>但透過確認才發現，「巴黎」跟「蜜月」這兩個分頁的表格格式跟其他趟旅行不同 — 「計算金額」不一定在 D 欄。</p><p>這次學到的原則： 處理真實世界的資料時，「寫死欄位位置」是最脆弱的假設。只要有一筆資料格式跟預期不同，整段邏輯就可能悄悄算錯而不自知。動態尋找標籤、明確標註「無法處理的例外」，比起硬套邏輯更穩健、也更誠實。</p><p>最終處置： 因為巴黎、蜜月這兩個分頁本來就是實驗性質建立的，最後選擇直接在 Google Sheet 上刪除這兩個分頁，從資料源頭排除問題，而不是讓程式邏輯遷就不一致的格式。</p><h4>問題二：新增 update_trip_budget 工具後，Claude 沒有反應新工具</h4><p><strong>現象：</strong> 加入第四個工具的程式碼後，問 Claude「可以改預算上限嗎」，仍然回答「我只有三個工具，沒辦法改」。</p><p><strong>原因：</strong> Claude Desktop 只有在<strong>完全重啟</strong>時才會重新讀取 MCP server 的工具清單。單純開新對話、或關閉對話視窗，並不會觸發重新載入。</p><p><strong>解法：</strong> 用 Cmd+Q 完整結束 Claude Desktop（不是關視窗），再重新打開，才能讀到新增的工具。</p><p>這次學到的原則： MCP server 的工具清單，是 client（這裡是 Claude Desktop）在啟動當下去問 server 拿到的，不是即時同步的。每次修改 server 程式碼（尤其是新增/修改工具宣告），都要記得完整重啟 client 端才會生效。</p><h3>七、串接 Claude Desktop</h3><h4>設定檔位置（macOS）</h4><pre>~/Library/Application Support/Claude/claude_desktop_config.json</pre><h4>設定內容</h4><p>在既有的 mcpServers 物件中，加入新的一組設定（注意跟其他 server 設定之間要用逗號分隔，不要覆蓋掉既有內容）：</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;stock-price&quot;: {<br>      &quot;command&quot;: &quot;node&quot;,<br>      &quot;args&quot;: [&quot;/絕對路徑/stock-mcp-server/index.js&quot;]<br>    },<br>    &quot;travel-budget&quot;: {<br>      &quot;command&quot;: &quot;node&quot;,<br>      &quot;args&quot;: [&quot;/絕對路徑/sheets-mcp-server/index.js&quot;]<br>    }<br>  }<br>}</pre><p>stock-mcp-server 這個是之前練習用的，不在這次內容但也予以保留。設定完成後完整重啟 Claude Desktop，即可在對話框旁的 <strong>Connectors</strong> 選單中看到並啟用新的 server。</p><h3>八、成果驗證</h3><p>實際在 Claude Desktop 中用自然語言測試：</p><ul><li>✅「用 travel-budget 工具查一下 2609大邱這趟旅行還剩多少預算」→ 正確呼叫 get_trip_summary，回傳明細與剩餘可用金額</li><li>✅ 新增測試支出 →「add_expense」成功寫入指定分頁，並自動判斷該加到第幾列</li><li>✅「幫我改預算上限成 50000」→ 加入 update_trip_budget 工具並重啟後，成功修改</li></ul><h3>九、此次練習帶來的技術收穫</h3><ol><li>授權機制的實作經驗 — 第一次處理需要驗證身份才能存取的外部資源，理解了 Service Account 這種「免互動登入」的授權模式跟一般 OAuth 使用者登入流程的差異。</li><li>資料防禦性設計 — — 「巴黎/蜜月」欄位錯位事件，讓我實際體會到「不要假設外部資料永遠符合預期格式」這個原則，並學會用「動態尋找標籤」取代「寫死位置」的做法。</li><li>可讀寫（不只是唯讀）系統的設計考量 — — add_expense、update_trip_budget 涉及寫入操作，需要比純查詢更謹慎地處理「資料要寫到哪裡」、「如何避免覆蓋掉既有資料」等問題。</li><li>理解 MCP client 與 server 的生命週期 — — 工具清單不是即時同步，修改 server 端程式碼後，必須讓 client 重新啟動才能生效，這對之後除錯或迭代時的判斷很有幫助。</li></ol><h3>延伸：在 Claude Code 使用 Google Sheets MCP Server</h3><h3>Claude Code 設定總覽</h3><h4>1. 安裝</h4><pre>sudo npm install -g @anthropic-ai/claude-code</pre><h4>2. 啟動與登入</h4><p>在專案資料夾下執行：</p><pre>claude</pre><p>第一次啟動會問登入方式：</p><p>選項 用途 1. Claude account with subscription 用 Pro / Max / Team / Enterprise 訂閱額度，不額外計費 2. Anthropic Console account 用 API key，依 token 用量計費 3. 3rd-party platform 透過 Bedrock / Foundry / Vertex AI 存取（企業用）</p><p>選了 <strong>1</strong>，用個人email Claude Pro 訂閱登入。</p><h4>3. 串接 MCP Server（sheets-mcp-server）</h4><p>用自己寫的 sheets-mcp-server/index.js，stdio-based MCP server，用來操作 Google Sheets 旅遊記帳表。</p><p><strong>步驟一：註冊</strong></p><p>幫 Claude Code 註冊一個新的 MCP server：</p><pre>claude mcp add  &lt;名稱&gt;      -s user  --  node  &lt;啟動這個 server 的指令&gt;</pre><p>這邊寫：</p><pre>claude mcp add sheets-mcp -s user -- node /Users/jacy/Desktop/claude/sheets-mcp-server/index.js</pre><ul><li>-s user：註冊到使用者層級，任何資料夾下都能用</li><li>-s local（預設）：只在目前資料夾內可用</li></ul><p><strong>步驟二：確認註冊成功</strong></p><pre>claude mcp list</pre><p>反應結果：</p><pre>You have two MCP servers configured, both connected:<br>- claude.ai Google Drive — https://drivemcp.googleapis.com/mcp/v1<br>- sheets-mcp — node /Users/jacy/Desktop/claude/sheets-mcp-server/index.js</pre><p>兩個都顯示 connected，代表設定完成。(Claude.ai Google Drive 是一個「遠端」MCP server，網址開頭是 https://，代表它跑在 Google 的伺服器上，不是你電腦上的程式。這是之前在 claude.ai 網頁版有連接過 Google Drive，這個連接設定跟 Claude Code 是共用的，所以裝好 Claude Code 一開始就會看到它已經存在。)</p><p><strong>步驟三：在對話中使用</strong></p><p>不用打指令，直接用自然語言下需求即可，例如：</p><pre>check the sheets-mcp trip stats</pre><p>Claude Code 會自動判斷該呼叫 sheets-mcp-server 裡定義的哪個 tool（例如 add_expense 之類）來完成。</p><h4>4. 安全提醒</h4><ul><li>私鑰檔案（如 travel-budget-mcp-*.json）只留在本機，Claude 呼叫時不會外傳</li><li>若要移除某個 server：</li></ul><pre>claude mcp remove sheets-mcp</pre><p>設定已經完成，接下來可以直接把它當日常工具用：改程式、查資料、串自己的工具，都用自然語言描述需求就好。</p><p>本文件為個人學習歷程紀錄，記錄實作過程、遇到的問題與解法，作為未來回顧或延伸寫作素材。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d16d6e2e6e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP 架構初探]]></title>
            <link>https://jacychu.medium.com/mcp-%E6%9E%B6%E6%A7%8B%E5%88%9D%E6%8E%A2-ffaa5593dbbb?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffaa5593dbbb</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-architecture]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 08:57:09 GMT</pubDate>
            <atom:updated>2026-06-18T08:58:03.542Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Agent 透過標準化協議，理解並使用外部系統能力</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbwEnnXkcY8UyPBSydMUKw.png" /></figure><p>最近在研究 <a href="https://modelcontextprotocol.io/docs/getting-started/intro">MCP（Model Context Protocol）</a>，其核心目標，是讓 AI App / AI Agent 可以用一種標準化方式，連接外部系統、讀取資料、呼叫工具，甚至使用預先設計好的提示詞流程。官方文件也把 MCP 形容成 AI 應用程式的 USB-C 連接埠，用來連接不同資料來源、工具與工作流程。</p><h4>這篇文章分成 3 個部分</h4><ol><li>MCP 架構中，AI Agent 怎麼連到產品？</li><li>MCP 通訊分成兩層：Data Layer 和 Transport Layer</li><li>AI Agent 怎麼知道 Server 有哪些能力？</li></ol><h3>Part 1：MCP 架構中，AI Agent 怎麼連到產品？</h3><p>MCP 採用的是 <strong>client-server 架構</strong>。</p><p>在 MCP 裡，主要有三個角色：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*2C9upcEj7WsyF1IIjJux5w.png" /></figure><p>官方架構文件也說明，MCP 是一種 <strong>client-host-server architecture</strong>，一個 Host 可以執行多個 Client，每個 Client 再與不同 Server 溝通。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwR1zpDEhOe_JfKHm0WNXA.png" /></figure><h4>用百貨公司來比喻 MCP 架構</h4><p>假設我們把一間百貨公司想成一個 AI Host。</p><p>百貨公司裡面有很多不同專線：</p><ul><li>停車專線</li><li>商品專線</li><li>餐飲專線</li></ul><p>每一條專線背後，都連到不同的系統：</p><ul><li>停車系統</li><li>庫存系統</li><li>訂位系統</li></ul><p>也就是說，Host 不會直接把所有產品能力混在一起管理，而是透過不同 MCP Client，分別連接不同 MCP Server。</p><p>這樣的好處是：</p><ul><li>每個 Server 可以專注在自己的產品能力</li><li>Host 可以同時管理多個 Server</li><li>不同系統之間的責任邊界比較清楚</li><li>權限與安全性也比較容易控管</li></ul><h3>Part 2：MCP 通訊分成兩層：Data Layer 和 Transport Layer</h3><p>理解 MCP 時，很重要的一點是：MCP 的通訊不是只有「怎麼連線」，還包含「訊息本身代表什麼」。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieP25Qce9RB4v8rmPUZTiQ.png" /></figure><p>Data Layer 定義 MCP 訊息「要說什麼、代表什麼」；Transport Layer 則負責「怎麼把訊息送出去、怎麼把結果送回來」。官方文件也將 MCP 分成 Data Layer 與 Transport Layer。Data Layer 主要處理 JSON-RPC 協議、生命週期管理，以及 tools、resources、prompts、notifications 等核心 primitive；Transport Layer 則處理 client 與 server 之間的實際通訊方式。</p><h4>為什麼要分成兩層？</h4><p>這樣設計的好處是：同一套 MCP 訊息，可以換不同傳送方式，而上層語意不用重寫。</p><p>例如：</p><ul><li>本機 Demo 時，可以用 stdio</li><li>正式產品整合時，可以換成 Streamable HTTP</li><li>但 tools/list、tools/call、resources/read 這些 MCP 訊息概念仍然可以維持一致</li></ul><p>這有點像同一封信，你可以用郵局寄，也可以用快遞寄，甚至用 Email 傳。寄送方式不同，但信件內容本身不需要整個重寫。</p><h4>Stdio vs Streamable HTTP</h4><p>MCP 目前常見的 Transport Layer 方式包含 stdio 與 Streamable HTTP。官方規格也提到 MCP 使用 JSON-RPC 編碼訊息，並定義了 stdio 與 Streamable HTTP 這兩種標準傳輸方式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlqXuNEy8QLdKrqfq_4S1A.png" /></figure><h3>Part 3：AI Agent 怎麼知道 Server 有哪些能力？</h3><p>AI 不是憑空知道產品功能。</p><p>它需要透過 MCP Client 和 MCP Server 的互動，先取得 Server 提供的能力清單，才知道自己可以做什麼。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSKzyDks89vYy7bJDNwy7w.png" /></figure><p>官方 lifecycle 文件也說明，MCP 連線生命週期包含 Initialization、Operation、Shutdown，其中 Initialization 負責 capability negotiation 與 protocol version agreement。</p><h4>Initialization：Server 先宣告自己支援哪些能力</h4><p>在 Initialization 階段，Server 會宣告自己支援哪些能力。</p><pre>{<br>  &quot;capabilities&quot;: {<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;resources&quot;: {<br>      &quot;subscribe&quot;: true,<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;prompts&quot;: {<br>      &quot;listChanged&quot;: true<br>    }<br>  }<br>}</pre><p>這段 capabilities 可以理解成：Server 先告訴 Client：「我支援哪些類型的功能，以及這些功能是否支援變更通知。」</p><p>例如：</p><ul><li>tools.listChanged: true<br> 代表工具清單變更時，Server 可以通知 Client。</li><li>resources.subscribe: true<br> 代表 Client 可以訂閱某個 resource 的變化。</li><li>resources.listChanged: true<br> 代表 resource 清單變動時，Server 可以通知 Client。</li><li>prompts.listChanged: true<br> 代表 prompt 模板清單變更時，Server 可以通知 Client。</li></ul><p>重點是：沒有宣告的能力，Client 不會假設 Server 有支援。所以 capabilities 是 MCP Client 和 Server 之間建立共識的第一步。</p><p>以上是MCP 架構初探的內容。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffaa5593dbbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用 n8n + OpenAI 做一個圖片 OCR 工具]]></title>
            <link>https://jacychu.medium.com/%E7%94%A8-n8n-openai-%E5%81%9A%E4%B8%80%E5%80%8B%E5%9C%96%E7%89%87-ocr-%E5%B7%A5%E5%85%B7-ca56fef96c08?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca56fef96c08</guid>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 02:11:22 GMT</pubDate>
            <atom:updated>2026-02-04T02:32:39.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>前端負責 UI，n8n 當流程後端，OpenAI 負責 AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlaYOx5zo1PjKdXkTw3XAA.png" /></figure><h4>n8n</h4><p>是一個「把很多事情自動串起來做」的工具。</p><p>功能清單：</p><ul><li>🔗 <strong>串系統</strong>：Google、Slack、Notion、GitHub、MySQL、API 都能接</li><li>⏰ <strong>定時做事</strong>：每天、每小時、自訂時間自動跑</li><li>🧠 <strong>有判斷邏輯</strong>：if / else、迴圈、條件分支</li><li>📦 <strong>資料轉換</strong>：整理 JSON、格式轉換、過濾資料</li><li>🧑‍💻 <strong>工程師友善</strong>：可以寫 JavaScript、打 API</li><li>🏠 <strong>可自己架</strong>：資料不丟雲端，放公司或自己主機</li></ul><h3>什麼人適合用 n8n？</h3><ul><li>👨‍💻 後端 / 前端工程師</li><li>🧑‍🔧 DevOps / SRE</li><li>🏢 內部系統很多的公司</li><li>🤖 想做「自動化流程」但不想寫一堆服務的人</li></ul><p>n8n 是可以用拖拉＋一點程式，把各種系統「自動接起來」的工具。</p><p>n8n官方提供雲端試驗版&amp;自建版本</p><ul><li>n8n 雲端試驗版：👉 註冊就能用，什麼都不用管，適合快速體驗流程。(免費試用14天)</li><li>n8n Docker 自建：👉 自己架自己管，但資料全在自己手上、最自由、適合長期或公司用。</li></ul><p>目前筆者採用雲端試驗版。</p><h3>實作 step by step</h3><p>最近研究 n8n，在構思可以用什麼實作當練習，想到之前有用Vue結合OpenAI API 做過OCR工具。</p><p>📝 文章：<a href="https://jacychu.medium.com/%E5%89%8D%E5%BE%8C%E7%AB%AF%E9%99%A4%E9%8C%AF%E5%88%A9%E5%99%A8-%E5%BE%9E%E6%88%AA%E5%9C%96%E5%88%B0-json-%E7%9A%84%E8%87%AA%E5%8B%95%E5%8C%96%E5%B7%A5%E5%85%B7-3756871776b4">前後端除錯利器：從截圖到 JSON 的自動化工具</a></p><p>藉由此工具做發想，我用 n8n實作：<br>上傳圖片 → 丟給 OpenAI 做 OCR → 回傳辨識出的文字</p><p>技術部分：前端上傳圖片 → n8n Webhook → OCR（OpenAI）＋判斷語言→<br> Code node 整理文字 → Webhook 回傳 JSON</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErutTkz-LgWsz3GqUDWzZA.png" /></figure><h4>step1 前端 ocr.html</h4><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;title&gt;Image OCR&lt;/title&gt;<br>  &lt;style&gt;<br>    body { font-family: sans-serif; max-width: 800px; margin: 30px auto; }<br>    pre { background: #f5f5f5; padding: 12px; white-space: pre-wrap; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Upload Image → OCR&lt;/h2&gt;<br><br>  &lt;input type=&quot;file&quot; id=&quot;file&quot; accept=&quot;image/*&quot; /&gt;<br>  &lt;br&gt;&lt;br&gt;<br>  &lt;button id=&quot;btn&quot;&gt;Analyze&lt;/button&gt;<br><br>  &lt;h3&gt;Result&lt;/h3&gt;<br>  &lt;pre id=&quot;result&quot;&gt;(empty)&lt;/pre&gt;<br><br>&lt;script&gt;<br>const WEBHOOK_URL = &quot;https://jacy.app.n8n.cloud/webhook/xxx&quot;; &lt;!-- 可替換成自己的WEBHOOK_URL --&gt;<br><br>function toBase64(file) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const reader = new FileReader();<br>    reader.onload = () =&gt; resolve(reader.result);<br>    reader.onerror = reject;<br>    reader.readAsDataURL(file);<br>  });<br>}<br><br>document.getElementById(&quot;btn&quot;).onclick = async () =&gt; {<br>  const f = document.getElementById(&quot;file&quot;).files[0];<br>  if (!f) return alert(&quot;Please choose an image&quot;);<br><br>  const base64 = await toBase64(f);<br>  document.getElementById(&quot;result&quot;).textContent = &quot;Processing...&quot;;<br><br>  const res = await fetch(WEBHOOK_URL, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({ image: base64 })<br>  });<br><br>  const text = await res.text();<br>  document.getElementById(&quot;result&quot;).textContent = text;<br>};<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>其中的 WEBHOOK_URL可以換成個人的。</p><h4>step2 n8n Webhook</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DguOvuZQZwcENpRSmMEkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Nft0OTH_6Qnl5Dj3P8bNw.png" /></figure><ul><li>這個 Webhook 設定成 用 POST 方法接收請求，路徑是 /image-ocr，外部系統只要呼叫這個 URL 就會觸發流程。</li><li>回應方式設定為 由「Respond to Webhook」節點決定，代表流程跑完後要回傳什麼、什麼時候回傳，由後面的節點控制。</li></ul><h4>step3 edit fields</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmYOhevZdo3BdfGa9-aRLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbGTF4ZVqluizxM4er61kw.png" /></figure><ul><li>這個節點從 Webhook 傳進來的 body 中，把 image 的 base64 資料取出並存成欄位 base64Raw。</li><li>透過 split(&#39;,&#39;)[1] 去掉 data:image/...;base64, 的前綴，只留下純 base64 內容給後續流程使用。</li></ul><p>為什麼要多加這個而不是直接送？因為 Webhook 傳進來的圖片通常長這樣： data:image/png;base64,iVBORw0KGgoAAA... 但大多數 OCR / AI / 影像 API 要的其實是：純 base64 資料本身（iVBORw0KGgoAAA...）</p><h4>step4 convert file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*686SWoPn-FkGYOHXGnyIFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFDvGFWnhzRxhcI_o4RHMg.png" /></figure><ul><li>這個節點把 base64Raw 的字串 轉成實際的檔案，並存成 binary 欄位 data，讓後面的節點把它當「圖片檔」使用。</li><li>之所以要加這一步，是因為很多 OCR 或檔案型 API 只吃檔案（binary / multipart）不吃 base64 字串，不轉的話後面通常會直接失敗。</li></ul><h4>step5 openAI分析圖片</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrE7ib3U2EyOQoJnfcvCNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwypT7k8HrCpNAPQrytMrg.png" /></figure><ul><li>這個節點把上一步轉好的圖片檔送進 OpenAI 影像模型（GPT-4o-mini），同時做 OCR 並偵測圖片中出現的所有語言。</li><li>模型依照你在 Text Input 裡定義的格式，直接回傳結構化 JSON（文字、各語言與信心分數、主要語言），方便後續流程與前端使用。</li></ul><p>Text Input (Prompt)內容：</p><pre>Please extract all text from this image (OCR), keep line breaks.<br><br>Then detect ALL languages present in the extracted text (not only the primary one).<br>Return JSON only:<br>{<br>  &quot;text&quot;: &quot;&lt;extracted text&gt;&quot;,<br>  &quot;languages&quot;: [<br>    {&quot;code&quot;: &quot;&lt;ISO 639-1&gt;&quot;, &quot;confidence&quot;: 0.0}<br>  ],<br>  &quot;primary_language&quot;: &quot;&lt;ISO 639-1 or &#39;mixed&#39;&gt;&quot;<br>}</pre><p>ISO 639–1 是「語言的國際標準代碼」，每一種語言都有一個 固定的 2 個英文字母代碼，用來在系統之間表示「這是哪一種語言」。</p><h4>step6 寫JS處理產出格式</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJYJg-nGCJErf4UR-bBlXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdiFWHw0uzMdBQCCgQaASQ.png" /></figure><ul><li>這個 JavaScript 節點把 OpenAI 節點回傳的 JSON 字串解析成真正的物件，取出 OCR 文字、語言清單與主要語言。</li><li>最後輸出成乾淨結構（text / languages / primary_language），讓後面的 Webhook 可以直接回傳或前端直接使用。</li></ul><p>JS內容：</p><pre>const item = $input.first();<br>const rawText = item.json?.[&quot;0&quot;]?.content?.[0]?.text ?? &#39;&#39;;<br><br>let parsed;<br>try {<br>  parsed = JSON.parse(rawText);<br>} catch (e) {<br>  parsed = {<br>    text: rawText,<br>    languages: [],<br>    primary_language: &#39;unknown&#39;,<br>  };<br>}<br><br>return [<br>  {<br>    json: {<br>      text: parsed.text ?? &#39;&#39;,<br>      languages: parsed.languages ?? [],<br>      primary_language:<br>        parsed.primary_language ?? parsed.language ?? &#39;unknown&#39;,<br>    },<br>  },<br>];</pre><h4>step7 webhook response</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWR-97Em0PnCO6Vw6uX9aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B--0TFi7bzXUwcBO8z6j2w.png" /></figure><ul><li>這個節點把前一個 JavaScript 節點整理好的結果，直接當作 Webhook 的 HTTP 回應內容回傳給前端。</li><li>回傳格式是乾淨的 JSON（文字、語言清單、主要語言），前端可以直接解析使用，不需要再額外處理。</li></ul><h4>實作成果</h4><p>測試圖片：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*TVNv9ehzViW3TnVe356E2g.png" /><figcaption>ocr_test_img</figcaption></figure><p>這張圖片包含了1.中文zh 2.英文en 3.西班牙文es</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2ZqhO2q7A4TiL5rvNvJ5w.gif" /></figure><p>測試成果成功，上面操作影片使用test mode，實測前要先按下Execute Workflow按鈕，如果正式發布成production mode，要記得改html中的WEBHOOK_URL。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca56fef96c08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從 0 開始的富文本編輯器]]></title>
            <link>https://jacychu.medium.com/%E5%BE%9E-0-%E9%96%8B%E5%A7%8B%E7%9A%84%E5%AF%8C%E6%96%87%E6%9C%AC%E7%B7%A8%E8%BC%AF%E5%99%A8-be8606ffae98?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/be8606ffae98</guid>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 09:46:36 GMT</pubDate>
            <atom:updated>2026-01-28T07:48:26.573Z</atom:updated>
            <content:encoded><![CDATA[<h4>Trumbowyg, Summernote, Quill, MediumEditor 比較</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kteadzp6du30GsQNjBsOog.png" /></figure><h4>WYSIWYG 富文本編輯器</h4><p>WYSIWYG (What You See Is What You Get) Rich Text Editor<br>一種讓使用者不需要撰寫 HTML，就能直接在網頁上編輯文字格式，且編輯畫面即為最終顯示結果的工具。</p><h4>Trumbowyg, Summernote, Quill, MediumEditor 比較</h4><p>功能完整派 → Summernote<br>輕量可控派 → Trumbowyg<br>資料驅動派 → Quill<br>極簡內容派 → MediumEditor</p><h4>比較套件大小</h4><p>NPM套件包下載下來大小(包含原始碼、文件、範例與多版本 build，並不等於實際網頁載入大小。)<br>Trumbowyg：約 1.1 MB<br>Summernote：約 8 MB<br>Quill：約 2.89 MB (Quill-Delta：93 KB)<br>(Delta 對 Quill 來說是引擎的一部分，不是可選插件。)<br>Medium-Editor：約 1.8 MB</p><p>實際網頁載入大小比較：<br>trumbowyg.min.js 28K trumbowyg.min.css 19K (共47K)<br>summernote.min.js 169K summernote.min.css 20K (共189K)<br>quill.js 205K quill.snow.css 25K (225K)<br>medium-editor.min.js 103K medium-editor.min.css 5K (共108K)</p><h3>📝 Trumbowyg 介紹</h3><p>Trumbowyg 是一款同樣基於 jQuery 的 輕量級富文本編輯器，設計理念明確： 「只提供實務上最常用的功能，其他的交給插件或自行擴充。」Trumbowyg 的核心套件非常小，初始化速度快，預設工具列簡潔，特別適合用在 後台表單、設定頁、簡易內容輸入欄位 這類場景。</p><p>Trumbowyg 的特色包括：</p><ul><li>套件體積小、載入速度快</li><li>不依賴 Bootstrap，樣式相對乾淨</li><li>依賴 jQuery</li><li>提供清楚的 plugin 機制，可依需求擴充功能</li><li>輸出的 HTML 結構相對簡單</li></ul><p>Trumbowyg 不像完整文字處理器那麼華麗，但在功能夠用的前提下，能有效降低專案複雜度與前端負擔，是偏向 實用取向 的選擇。</p><p>CDN引用</p><p>JS<br><a href="https://code.jquery.com/jquery-3.6.0.min.js">https://code.jquery.com/jquery-3.6.0.min.js</a><br><a href="https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/trumbowyg.min.js">https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/trumbowyg.min.js</a></p><p>CSS<br><a href="https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/ui/trumbowyg.min.css">https://cdn.jsdelivr.net/npm/trumbowyg@2.27.3/dist/ui/trumbowyg.min.css</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4V9udsUjSNPCGgUJCz_xsA.png" /></figure><pre>&lt;div id=&quot;editor&quot;&gt;Hello Trumbowyg&lt;/div&gt;</pre><pre>$(&#39;#editor&#39;).trumbowyg();</pre><p>By default, btns option value is:</p><pre>$(&#39;.simple-editor&#39;).trumbowyg({<br>    btns: [<br>        [&#39;viewHTML&#39;],<br>        [&#39;undo&#39;, &#39;redo&#39;], // Only supported in Blink browsers<br>        [&#39;formatting&#39;],<br>        [&#39;strong&#39;, &#39;em&#39;, &#39;del&#39;],<br>        [&#39;superscript&#39;, &#39;subscript&#39;],<br>        [&#39;link&#39;],<br>        [&#39;insertImage&#39;],<br>        [&#39;justifyLeft&#39;, &#39;justifyCenter&#39;, &#39;justifyRight&#39;, &#39;justifyFull&#39;],<br>        [&#39;unorderedList&#39;, &#39;orderedList&#39;],<br>        [&#39;horizontalRule&#39;],<br>        [&#39;removeformat&#39;],<br>        [&#39;fullscreen&#39;]<br>    ]<br>});</pre><h4>Trumbowyg 官方 plugins</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*m9rD8X8hqUSYklXNZkeKLA.png" /></figure><p>常見包含</p><ul><li>upload（local端上傳圖片）</li><li>table（要自己加寫css相關設定）</li><li>colors</li><li>fontsize</li></ul><h4>範例程式碼：(要先<a href="https://www.npmjs.com/package/trumbowyg">npm install trumbowyg</a>)</h4><p>2024–03–06 仍有發版更新，相對有在更新</p><p>此範例包含了color與table plugin</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>  &lt;title&gt;Trumbowyg local test&lt;/title&gt;<br><br>  &lt;!-- Trumbowyg CSS --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/trumbowyg/dist/ui/trumbowyg.min.css&quot; /&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/trumbowyg/dist/plugins/table/ui/trumbowyg.table.min.css&quot; /&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/trumbowyg/dist/plugins/colors/ui/trumbowyg.colors.min.css&quot;&gt;<br><br>&lt;/head&gt;<br>&lt;style&gt;<br>  .trumbowyg-editor table {<br>    border-collapse: collapse;<br>    width: 100%;<br>  }<br><br>  .trumbowyg-editor td,<br>  .trumbowyg-editor th {<br>    border: 1px solid #ccc;<br>    padding: 6px;<br>  }<br><br>  .preview table {<br>    border-collapse: collapse;<br>    width: 100%;<br>  }<br>  .preview td, .preview th {<br>    border: 1px solid #ccc;<br>    padding: 6px;<br>  }<br><br>  .layout {<br>    display: grid;<br>    grid-template-columns: 1fr 1fr;<br>    gap: 16px;<br>    align-items: start;<br>  }<br><br>  .panel {<br>    border: 1px solid #ddd;<br>    padding: 12px;<br>    border-radius: 8px;<br>  }<br><br>  .preview {<br>    min-height: 260px;<br>    padding: 12px;<br>    border: 1px dashed #ccc;<br>    background: #fff;<br>  }<br><br>  .actions {<br>    margin-top: 12px;<br>    display: flex;<br>    gap: 12px;<br>    align-items: center;<br>  }<br><br>  #output {<br>    width: 100%;<br>    margin-top: 12px;<br>    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;<br>  }<br><br>&lt;/style&gt;<br>&lt;body&gt;<br>  &lt;h3&gt;Trumbowyg (local) - Live Preview + Export&lt;/h3&gt;<br><br>  &lt;div class=&quot;layout&quot;&gt;<br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Editor&lt;/h4&gt;<br>      &lt;div id=&quot;editor&quot;&gt;Hello Trumbowyg&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Preview&lt;/h4&gt;<br>      &lt;div id=&quot;preview&quot; class=&quot;preview&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;actions&quot;&gt;<br>    &lt;button id=&quot;btn-export&quot; type=&quot;button&quot;&gt;Export HTML&lt;/button&gt;<br>    &lt;span id=&quot;info&quot;&gt;&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;textarea id=&quot;output&quot; rows=&quot;8&quot; placeholder=&quot;Exported HTML will appear here...&quot;&gt;&lt;/textarea&gt;<br><br>  &lt;!-- jQuery --&gt;<br>  &lt;script src=&quot;./node_modules/jquery/dist/jquery.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Trumbowyg core --&gt;<br>  &lt;script src=&quot;./node_modules/trumbowyg/dist/trumbowyg.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Table plugin --&gt;<br>  &lt;script src=&quot;./node_modules/trumbowyg/dist/plugins/table/trumbowyg.table.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- color plugin --&gt;<br>  &lt;script src=&quot;./node_modules/trumbowyg/dist/plugins/colors/trumbowyg.colors.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;script&gt;<br>    const $editor = $(&#39;#editor&#39;);<br>    const $preview = $(&#39;#preview&#39;);<br>    const $output = $(&#39;#output&#39;);<br>    const $info = $(&#39;#info&#39;);<br><br>    function updatePreview() {<br>      const html = $editor.trumbowyg(&#39;html&#39;);<br>      $preview.html(html);<br><br>      // 可選：顯示純文字字數<br>      const textLen = $preview.text().trim().length;<br>      $info.text(`Text length: ${textLen}`);<br>    }<br><br>    $editor.trumbowyg({<br>      svgPath: &#39;./node_modules/trumbowyg/dist/ui/icons.svg&#39;,<br>      btns: $.trumbowyg.defaultOptions.btns.concat([<br>        [&#39;foreColor&#39;, &#39;backColor&#39;],<br>        [&#39;table&#39;]<br>      ]),<br>      autogrow: true<br>    });<br><br>    // 初始化後先渲染一次<br>    updatePreview();<br><br>    // 即時更新（打字/操作工具列都會觸發）<br>    $editor.on(&#39;tbwchange&#39;, function () {<br>      updatePreview();<br>    });<br><br>    // 輸出 HTML（按鈕）<br>    $(&#39;#btn-export&#39;).on(&#39;click&#39;, function () {<br>      const html = $editor.trumbowyg(&#39;html&#39;);<br>      $output.val(html);<br>      $output.focus();<br>      $output.select();<br>    });<br>  &lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLheYWC38FytA0UPUjT8kQ.png" /></figure><h3>📝 Summernote 介紹</h3><p>Summernote 是一款基於 jQuery 的開源 WYSIWYG（所見即所得）富文本編輯器，主打「快速上手、開箱即用」。它提供完整的工具列（文字樣式、清單、連結、圖片等），操作體驗接近 Word 或 Google Docs，非常適合用在 CMS、公告編輯、內容管理後台。</p><p>Summernote 與 Bootstrap 的整合度很高，官方提供不同 Bootstrap 版本的 build（bs3 / bs4 / bs5），如果專案本身已經使用 Bootstrap，UI 風格可以自然融入，不需要額外客製太多樣式。</p><p>Summernote 的特色包括：</p><ul><li>功能齊全、設定簡單</li><li>幾乎不用額外設定就能直接使用</li><li>社群成熟、文件完整</li><li>依賴 Bootstrap</li><li>依賴 jQuery</li></ul><p>Summernote的套件體積與依賴也比較多，實際使用時通常需要同時引入 jQuery 與 Bootstrap，整體載入成本較高，較適合「內容編輯導向」而非極度追求輕量的場景。</p><p>CDN引用</p><p>JS<br><a href="https://code.jquery.com/jquery-3.6.0.min.js">https://code.jquery.com/jquery-3.6.0.min.js</a><br><a href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js">https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js</a><br><a href="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-bs4.min.js">https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-bs4.min.js</a></p><p>CSS<br><a href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css</a><br><a href="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-bs4.min.css">https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-bs4.min.css</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrYEQ-AOfUd8Sstz-V_dhw.png" /></figure><pre>&lt;div id=&quot;editor&quot;&gt;Hello Summernote&lt;/div&gt;</pre><pre>$(&#39;#editor&#39;).summernote({<br>  height: 200<br>});</pre><h4>範例程式碼：(要先<a href="https://www.npmjs.com/package/summernote?activeTab=code">npm install summernote</a>)</h4><p>2024–10–09 仍有發版更新，相對有在更新</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;title&gt;Summernote minimal&lt;/title&gt;<br><br>  &lt;!-- Bootstrap CSS (必要) --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/bootstrap/dist/css/bootstrap.min.css&quot;&gt;<br><br>  &lt;!-- Summernote CSS --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/summernote/dist/summernote-lite.min.css&quot;&gt;<br><br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css&quot;&gt;<br><br>  &lt;style&gt;<br>    .layout {<br>      display: grid;<br>      grid-template-columns: 1fr 1fr;<br>      gap: 16px;<br>      align-items: start;<br>    }<br>    .panel {<br>      border: 1px solid #ddd;<br>      padding: 12px;<br>      border-radius: 8px;<br>    }<br>    .preview {<br>      min-height: 260px;<br>      padding: 12px;<br>      border: 1px dashed #ccc;<br>      background: #fff;<br>    }<br>    .actions {<br>      margin-top: 12px;<br>      display: flex;<br>      gap: 12px;<br>      align-items: center;<br>    }<br>    #output {<br>      width: 100%;<br>      margin-top: 12px;<br>      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;<br>    }<br>    /* 讓輸出 table 預覽也看得清楚 */<br>    .preview table { border-collapse: collapse; width: 100%; }<br>    .preview th, .preview td { border: 1px solid #ccc; padding: 6px; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;p-3&quot;&gt;<br><br>  &lt;h3&gt;Summernote - Live Preview + Export&lt;/h3&gt;<br><br>  &lt;div class=&quot;layout&quot;&gt;<br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Editor&lt;/h4&gt;<br>      &lt;div id=&quot;editor&quot;&gt;Hello Summernote&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Preview&lt;/h4&gt;<br>      &lt;div id=&quot;preview&quot; class=&quot;preview&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;actions&quot;&gt;<br>    &lt;button id=&quot;btn-export&quot; type=&quot;button&quot; class=&quot;btn btn-primary btn-sm&quot;&gt;Export HTML&lt;/button&gt;<br>    &lt;span id=&quot;info&quot; class=&quot;text-muted&quot;&gt;&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;textarea id=&quot;output&quot; rows=&quot;8&quot; placeholder=&quot;Exported HTML will appear here...&quot;&gt;&lt;/textarea&gt;<br><br><br><br>  &lt;!-- jQuery --&gt;<br>  &lt;!-- &lt;script src=&quot;./node_modules/jquery/dist/jquery.min.js&quot;&gt;&lt;/script&gt; --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js&quot;&gt;&lt;/script&gt;<br><br><br>  &lt;!-- Bootstrap JS (bundle) --&gt;<br>  &lt;script src=&quot;./node_modules/bootstrap/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Summernote JS --&gt;<br>  &lt;script src=&quot;./node_modules/summernote/dist/summernote-lite.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;script&gt;<br>    const $editor = $(&#39;#editor&#39;);<br>    const $preview = $(&#39;#preview&#39;);<br>    const $output = $(&#39;#output&#39;);<br>    const $info = $(&#39;#info&#39;);<br><br>    function updatePreview() {<br>      const html = $editor.summernote(&#39;code&#39;);<br>      $preview.html(html);<br>      const textLen = $preview.text().trim().length;<br>      $info.text(`Text length: ${textLen}`);<br>    }<br><br>    $editor.summernote({<br>      height: 220,<br>      placeholder: &#39;Type here...&#39;,<br>      toolbar: [<br>        [&#39;style&#39;, [&#39;style&#39;]],<br>        [&#39;font&#39;, [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;, &#39;clear&#39;]],<br>        [&#39;color&#39;, [&#39;color&#39;]],           // color<br>        [&#39;para&#39;, [&#39;ul&#39;, &#39;ol&#39;, &#39;paragraph&#39;]],<br>        [&#39;table&#39;, [&#39;table&#39;]],           // table<br>        [&#39;insert&#39;, [&#39;link&#39;, &#39;picture&#39;]],<br>        [&#39;view&#39;, [&#39;codeview&#39;]]<br>      ]<br>    });<br><br>    updatePreview();<br><br>    // Summernote change event<br>    $editor.on(&#39;summernote.change&#39;, function () {<br>      updatePreview();<br>    });<br><br>    $(&#39;#btn-export&#39;).on(&#39;click&#39;, function () {<br>      const html = $editor.summernote(&#39;code&#39;);<br>      $output.val(html);<br>      $output.focus();<br>      $output.select();<br>    });<br>  &lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84xHidAnBScZraqznNRaaA.png" /></figure><h3>🎞️圖片影片Trumbowyg, Summernote比較</h3><h4>圖片</h4><ol><li>Trumbowyg 預設是用 URL 插入圖片。它的 upload plugin 是一個偏「完整上傳流程」的設計：選檔後，它會直接送到開發者設定的 serverPath（後端 API），後端回傳圖片 URL 後，再插入到內容中。所以Trumbowyg 的 upload plugin 本質上是走「真的上傳」，不是單純做本機預覽。</li><li>Summernote 在「插入圖片」上，常見有兩種方式：(1)用 URL 插入圖片&lt;img src=”<a href="https://">https://</a>...&quot;&gt; (2)用本機圖片直接預覽（把圖片轉成 data: / blob:，讓畫面先看得到），但「本機預覽」這種做法，不等於真的把圖片上傳到伺服器。如果要讓別人也看得到，最後還是需要把圖片上傳，換成真正的 URL。</li></ol><h4>影片</h4><ol><li>Trumbowyg 沒有內建「影片上傳」功能。影片用 &lt;video&gt;（或 &lt;iframe&gt;）的方式插入。</li><li>Summernote 沒有內建「影片上傳」功能。常見做法是把影片用 HTML 的 &lt;video&gt;（或 &lt;iframe&gt;）方式放進內容中，等於「插入影片網址/嵌入碼」。</li></ol><h3>📝 <strong>Quill 介紹</strong></h3><p>Quill 是一款「以模組化與可擴充性為核心」的現代富文本編輯器，主打開發者友善：你可以用清楚的 API 監聽內容變化、控制格式、客製工具列，並且用 Delta（JSON 形式） 來描述內容，讓資料交換與版本控制更穩定、可預期。整體定位比較像「可組裝的編輯器引擎」，而不是一個一體成形的文字處理器。</p><p>Quill 的特色包括：</p><ul><li>模組化架構：Toolbar、Clipboard、History 等都可按需組合與覆寫</li><li>Delta（JSON）為核心資料格式：更容易做到一致的內容表示與變更追蹤（相對純 HTML 更「可控」）</li><li>主題與外觀選擇：內建常見的 Snow / Bubble 主題（需額外引入對應 CSS）</li><li>格式（formats）與嵌入（embeds）完整：圖片、影片、公式等可透過模組擴充</li><li>純JS，不依賴jQuery/Bootstrap</li></ul><p>Quill 通常會比傳統 jQuery 型 WYSIWYG 更好施力；但相對地，開發者會更常花時間在「選配模組、訂規則、調行為」上，而不是開箱即用一路順到尾。</p><p>Delta 是 Quill 用來表示編輯內容與變更的「結構化資料格式（JSON）」，不是 HTML。</p><h4>傳統編輯器</h4><p>內容 = 一大串 HTML</p><pre>&lt;p&gt;&lt;b&gt;Hello&lt;/b&gt; world&lt;/p&gt;</pre><h4>Quill（Delta）</h4><p>內容 = 一組「插入什麼 + 套什麼格式」的指令</p><pre>{<br>  ops: [<br>    { insert: &quot;Hello&quot;, attributes: { bold: true } },<br>    { insert: &quot; world\n&quot; }<br>  ]<br>}</pre><ul><li><strong>HTML</strong>：長相</li><li><strong>Delta</strong>：編輯「做了什麼事」的紀錄</li></ul><h4>⭐與前兩個(Trumbowyg, Summernote)比較</h4><p>Quill 編輯本質是結構（JSON / Delta），而不是HTML<br>Quill 要插入圖片 / 影片需要高度客製化<br>Quill 內容乾淨度高，做undo很穩</p><h4>⭐ 什麼情況「一定選」Quill？</h4><ul><li>內容很多、會用很久</li><li>不想被亂貼搞壞格式</li><li>不需要使用者碰 HTML</li></ul><h4>範例程式碼：(要先<a href="https://www.npmjs.com/package/quill">npm install quill</a>)</h4><p>Quill 2.0 在 2024 年正式釋出，且官方有升級文件</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;zh-Hant&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>  &lt;title&gt;Quill local test - Live Preview + Export&lt;/title&gt;<br><br>  &lt;!-- Quill CSS theme --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/quill/dist/quill.snow.css&quot; /&gt;<br><br>  &lt;style&gt;<br>    body { margin: 16px; font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial; }<br>    .layout {<br>      display: grid;<br>      grid-template-columns: 1fr 1fr;<br>      gap: 16px;<br>      align-items: start;<br>    }<br>    .panel {<br>      border: 1px solid #ddd;<br>      border-radius: 8px;<br>      padding: 12px;<br>      background: #fff;<br>    }<br>    #editor {<br>      height: 240px;<br>    }<br>    .preview {<br>      min-height: 240px;<br>      border: 1px dashed #ccc;<br>      padding: 12px;<br>      background: #fff;<br>    }<br>    .actions {<br>      margin-top: 12px;<br>      display: flex;<br>      gap: 12px;<br>      align-items: center;<br>      flex-wrap: wrap;<br>    }<br>    textarea {<br>      width: 100%;<br>      margin-top: 12px;<br>      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;<br>    }<br>    /* 讓 preview 的 table/列表看得清楚（Quill 預設不支援 table，這是給你未來擴充用） */<br>    .preview table { border-collapse: collapse; width: 100%; }<br>    .preview th, .preview td { border: 1px solid #ccc; padding: 6px; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h3&gt;Quill (local) - Live Preview + Export&lt;/h3&gt;<br><br>  &lt;div class=&quot;layout&quot;&gt;<br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Editor&lt;/h4&gt;<br>      &lt;div id=&quot;editor&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;panel&quot;&gt;<br>      &lt;h4&gt;Preview (HTML)&lt;/h4&gt;<br>      &lt;div id=&quot;preview&quot; class=&quot;preview&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;actions&quot;&gt;<br>    &lt;button id=&quot;btn-export-html&quot; type=&quot;button&quot;&gt;Export HTML&lt;/button&gt;<br>    &lt;button id=&quot;btn-export-delta&quot; type=&quot;button&quot;&gt;Export Delta (JSON)&lt;/button&gt;<br>    &lt;span id=&quot;info&quot;&gt;&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;textarea id=&quot;output&quot; rows=&quot;10&quot; placeholder=&quot;Exported content will appear here...&quot;&gt;&lt;/textarea&gt;<br><br>  &lt;!-- Quill JS (UMD) --&gt;<br>  &lt;script src=&quot;./node_modules/quill/dist/quill.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;script&gt;<br>    // 1) Init quill<br>    const quill = new Quill(&#39;#editor&#39;, {<br>      theme: &#39;snow&#39;,<br>      placeholder: &#39;Type here...&#39;,<br>      modules: {<br>        toolbar: [<br>          [{ header: [1, 2, 3, false] }],<br>          [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;, &#39;strike&#39;],<br>          [{ color: [] }, { background: [] }],<br>          [{ align: [] }],<br>          [{ list: &#39;ordered&#39; }, { list: &#39;bullet&#39; }],<br>          [&#39;link&#39;, &#39;image&#39;],<br>          [&#39;clean&#39;]<br>        ]<br>      }<br>    });<br><br>    // Seed content<br>    quill.setText(&#39;Hello Quill&#39;);<br><br>    const previewEl = document.getElementById(&#39;preview&#39;);<br>    const outputEl = document.getElementById(&#39;output&#39;);<br>    const infoEl = document.getElementById(&#39;info&#39;);<br><br>    function updatePreview() {<br>      // Quill 編輯區內容在 .ql-editor 裡<br>      const html = document.querySelector(&#39;#editor .ql-editor&#39;).innerHTML;<br>      previewEl.innerHTML = html;<br><br>      const textLen = previewEl.textContent.trim().length;<br>      infoEl.textContent = `Text length: ${textLen}`;<br>    }<br><br>    // initial render<br>    updatePreview();<br><br>    // 2) Live preview: listen to changes<br>    quill.on(&#39;text-change&#39;, updatePreview);<br><br>    // 3) Export HTML<br>    document.getElementById(&#39;btn-export-html&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>      const html = document.querySelector(&#39;#editor .ql-editor&#39;).innerHTML;<br>      outputEl.value = html;<br>      outputEl.focus();<br>      outputEl.select();<br>    });<br><br>    // 4) Export Delta (JSON)<br>    document.getElementById(&#39;btn-export-delta&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>      const delta = quill.getContents();<br>      outputEl.value = JSON.stringify(delta, null, 2);<br>      outputEl.focus();<br>      outputEl.select();<br>    });<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4fZiJWw2REDKqcEJVk7dQ.png" /><figcaption>輸出HTML(不是Quill設計的核心)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCTkydsYV44qaKkP97_SIw.png" /><figcaption>輸出JSON</figcaption></figure><h3>📝 <strong>MediumEditor 介紹</strong></h3><p>MediumEditor 是一款模仿 Medium.com 編輯體驗的 inline（行內型）富文本編輯器，特色是「工具列浮在選取文字附近、互動很直覺」，而且它是 vanilla JavaScript 寫的，不強制依賴 jQuery 或 Bootstrap。預設使用者把其當「文字編輯器」，不是 HTML 編輯器。(不建議硬加上圖片影片)</p><p>MediumEditor 的特色包括：</p><ul><li>Inline 工具列體驗：選取文字就出現工具列，適合短內容、段落式編輯</li><li>零框架依賴：用原生 JS 實作，整合成本低</li><li>以 contenteditable 為基礎：直接把既有 DOM 變成可編輯區塊</li><li>可透過外掛延伸常見需求：例如圖片插入/上傳、Markdown 擴充等（多為社群外掛）</li><li>純JS，不依賴 jQuery/Bootstrap</li></ul><p>MediumEditor 操作體驗很像「把 Medium 那套選取即編輯的體驗搬進你的後台或頁面」。非常適合：少量富文本（粗體、連結、清單）、希望 UI 乾淨、不要一整套大型工具列。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*7fyWFt-MaAFD-3lScP3LAg.png" /></figure><h4>範例程式碼：(要先<a href="https://www.npmjs.com/package/medium-editor">npm install medium-editor</a>)</h4><p>GitHub Releases 最後是 2017–12–20，相較沒有在更新了</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;zh-Hant&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;title&gt;MediumEditor minimal&lt;/title&gt;<br><br>  &lt;!-- MediumEditor CSS --&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/medium-editor/dist/css/medium-editor.min.css&quot;&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./node_modules/medium-editor/dist/css/themes/default.min.css&quot;&gt;<br><br>  &lt;style&gt;<br>    body {<br>      margin: 24px;<br>      font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;<br>    }<br><br>    .editor {<br>      border: 1px solid #ddd;<br>      padding: 16px;<br>      min-height: 180px;<br>      border-radius: 8px;<br>    }<br><br>    .actions {<br>      margin-top: 12px;<br>    }<br><br>    textarea {<br>      width: 100%;<br>      margin-top: 12px;<br>      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, &quot;Liberation Mono&quot;, &quot;Courier New&quot;, monospace;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>  &lt;h3&gt;MediumEditor minimal test&lt;/h3&gt;<br><br>  &lt;div id=&quot;editor&quot; class=&quot;editor&quot; contenteditable=&quot;true&quot;&gt;<br>    Hello MediumEditor<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;actions&quot;&gt;<br>    &lt;button id=&quot;btn-export&quot; type=&quot;button&quot;&gt;Export HTML&lt;/button&gt;<br>  &lt;/div&gt;<br><br>  &lt;textarea id=&quot;output&quot; rows=&quot;8&quot; placeholder=&quot;Exported HTML will appear here...&quot;&gt;&lt;/textarea&gt;<br><br>  &lt;!-- MediumEditor JS --&gt;<br>  &lt;script src=&quot;./node_modules/medium-editor/dist/js/medium-editor.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;script&gt;<br>    // 1) Init editor<br>    const editor = new MediumEditor(&#39;#editor&#39;, {<br>      placeholder: {<br>        text: &#39;Type here...&#39;,<br>        hideOnClick: true<br>      },<br>      toolbar: {<br>        buttons: [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;, &#39;anchor&#39;, &#39;unorderedlist&#39;, &#39;orderedlist&#39;]<br>      }<br>    });<br><br>    // 2) Export HTML<br>    document.getElementById(&#39;btn-export&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>      const html = document.getElementById(&#39;editor&#39;).innerHTML;<br>      document.getElementById(&#39;output&#39;).value = html;<br>    });<br>  &lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pGvwOniQ8PwQvnb-L8ySw.png" /></figure><h3>小結</h3><p>這四套都屬於 WYSIWYG 富文本編輯器，但它們的定位其實差很大，可以用一句話快速分類：</p><ul><li>功能完整派 → Summernote：開箱即用、工具列最齊全，適合 CMS/公告/內容管理後台；代價是依賴多（jQuery + Bootstrap），整體載入成本也最高。</li><li>輕量可控派 → Trumbowyg：核心小、工具列簡潔、用 plugin 擴充最常見需求，適合後台表單與設定頁；缺點是仍依賴 jQuery，且內容結構主要以 HTML 為主，控制力不如 Quill。</li><li>資料驅動派 → Quill：用 Delta（JSON） 當內容模型，強項在「格式規範、貼上規則、擴充自訂內容元件（embeds）」這類工程化需求；代價是更像在組裝引擎，通常需要花時間選配模組與調整行為。</li><li>極簡內容派 → MediumEditor：主打 inline 編輯體驗、零框架依賴，適合少量格式（粗體/連結/清單）的乾淨輸入區；若需求變複雜（表格、圖片上傳、嚴格格式控制），通常要依賴外掛或額外開發。</li></ul><p>套件包實際網頁會載入的 min.js / css」大小比較：</p><ul><li>最輕量：Trumbowyg（47K）</li><li>最極簡、體積也小：MediumEditor（108K）</li><li>工程化但更重：Quill（225K，含 theme CSS）</li><li>功能最全但載入成本最高：Summernote（189K，且通常還要算 Bootstrap/jQuery）</li></ul><p>結論：<br>後台表單與簡易輸入 → Trumbowyg / MediumEditor<br>內容管理與編輯體驗優先 → Summernote<br>需要可控格式、結構化內容與擴充能力 → Quill</p><p>可以依需求選擇~</p><h3>進階比較</h3><h4>1. (進階比較) 從word文字貼過來乾淨度</h4><p>Word 內容包含：</p><ul><li>紅字（color）</li><li>藍字（color）</li><li>粗體（bold）</li><li>斜體（italic）</li><li>同一句內：顏色 + 粗體</li><li>超連結</li><li>中文為主（CJK）</li><li>從 Word 直接貼上（含 Word 專屬樣式）</li></ul><p>👉 這是 富文字編輯器最容易翻車的真實情境。</p><h4>Trumbowyg</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELJGNJ4EosyMnhg04IiTyg.png" /></figure><p>預覽樣式完整，但沒有清 Word 樣式</p><ul><li>mso-*</li><li>font-size: 13.5pt</li><li>Times New Roman</li><li>&lt;o:p&gt;, &lt;u1:p&gt;, &amp;nbsp;</li><li>多層 &lt;span&gt; 套 &lt;strong&gt; 套 &lt;em&gt;</li></ul><h4>Summernote</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsAUnSZNGoUBwg3gR72bbA.png" /></figure><p>預覽樣式完整，但沒有清 Word 樣式，和Trumbowyg結果幾乎差不多。</p><h4>Quill</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnqVhO3R0vQxQims97A7aw.png" /></figure><p>預覽樣式完整，格式也很乾淨。</p><h4>MediumEditor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esnZTvT3Yy7XaEmq3aP61w.png" /></figure><p>沒有裝plugin，所以樣式都沒出來。</p><h4>乾淨度比較小結：</h4><ul><li>如果你最在意 Word 貼上乾淨、長期可維護：選 Quill（圖片/影片也能做，但要自己整合上傳）</li><li>如果你要快速有圖片/影片功能：選 Summernote/Trumbowyg + 必做 HTML 清理</li></ul><h4>2. (進階比較) XSS 測試</h4><p>XSS ( <strong>Cross-Site Scripting ) </strong>是一種網站安全問題，指的是有人把惡意的 JavaScript 程式碼偷偷放進網站內容中，當其他使用者打開該頁面時，這些程式碼就會在他們的瀏覽器中執行。因為程式碼是從正常網站載入的，瀏覽器無法分辨是攻擊，可能導致帳號被盜、操作被冒用，或被導向不安全的網站。</p><p>🧪 Test1：最基本款攻擊</p><pre>&lt;script&gt;alert(&quot;XSS-1&quot;)&lt;/script&gt;</pre><p>Trumbowyg 直接跳 alert，編輯器 允許 script tag 進入 DOM</p><p>Summernote 至少有一層防護，會阻止最直接的 &lt;script&gt; tag</p><p>Quill 刻意不提供「直接輸入 HTML」的入口</p><p>MediumEditor沒跳 alert，是因為會清理「破壞編輯的東西」像是&lt;script&gt;為了編輯體驗，不是為了防攻擊</p><p>🧪 Test2：隱蔽一點的XSS</p><pre>&lt;img src=&quot;x&quot; onerror=&quot;alert(&#39;XSS-2&#39;)&quot;&gt;</pre><p>Trumbowyg 直接跳 alert，on* 事件屬性完全沒被處理</p><p>Summernote直接跳 alert</p><p>Quill 刻意不提供「直接輸入 HTML」的入口</p><p>MediumEditor沒跳 alert，但內部也沒特別處理</p><p>🧪 Test3：使用者互動XSS(點一下就中)</p><pre>&lt;a href=&quot;javascript:alert(&#39;XSS-3&#39;)&quot;&gt;click me&lt;/a&gt;</pre><p>Trumbowyg 惡意連結可以被正常存入</p><p>Summernote 惡意連結可以被正常存入</p><p>Quill 刻意不提供「直接輸入 HTML」的入口</p><p>MediumEditor沒跳 alert，但內部也沒特別處理</p><h4>安全比較小結：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Qv7Hf9Nd298Bg4HtSl-G6Q.png" /></figure><h4>安全補強</h4><p>所有編輯器「共通必做」的安全補強：後端 HTML Sanitizer<br>可以使用白名單（allowlist），只允許真的有需要的 tag / attr / protocol<br>舉例：</p><pre>Tags:<br>p, br, strong, em, ul, ol, li, a, img<br><br>Attributes:<br>a: href, title<br>img: src, alt<br><br>Allowed protocols:<br>http, https, mailto</pre><p>一定要移除的</p><ul><li>&lt;script&gt;</li><li>所有 on*（onerror, onclick…）</li><li>javascript: / data:（圖片除非你真的要 base64）</li><li>&lt;iframe&gt;（除非有列上白名單）</li></ul><h4>3. (進階比較)多國語系</h4><h4>(1) Trumbowyg</h4><p>有提供初始化一次設定好語系，沒有提供靈活切換。作法如下：</p><pre>&lt;!-- i18n langs (pick what you need) --&gt;<br>&lt;script src=&quot;./node_modules/trumbowyg/dist/langs/zh_tw.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;./node_modules/trumbowyg/dist/langs/zh_cn.min.js&quot;&gt;&lt;/script&gt;</pre><p>並在初始化設定部分加上語系指定：</p><pre>$editor.trumbowyg({<br>  lang:&#39;zh_cn&#39;, //這邊<br>  ...<br>});</pre><p>Trumbowyg 定位是：</p><ul><li>小跟輕量</li><li>無狀態（stateless-ish）</li><li>初始化一次就用</li></ul><p>核心設計年代（2013～2015）是 jQuery plugin 時代，不是 React/Vue 那種 reactive 狀態系統。</p><p>👉 它沒有「global state / re-render」的概念。</p><h4><strong>(2) </strong>Summernote</h4><p>有提供初始化一次設定好語系，沒有提供靈活切換。作法如下：</p><pre>&lt;!-- Summernote Lang --&gt;<br>&lt;script src=&quot;./node_modules/summernote/dist/lang/summernote-zh-TW.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;./node_modules/summernote/dist/lang/summernote-zh-CN.min.js&quot;&gt;&lt;/script&gt;</pre><p>並在初始化設定部分加上語系指定：</p><pre>$editor.summernote({<br>  lang: &#39;zh-TW&#39;,<br>  ...<br>});</pre><p>Summernote 跟 Trumbowyg 是「同一世代、同一類型」的編輯器，語系設計幾乎一模一樣。</p><h4>(3) Quill</h4><p>Quill 官方刻意不提供語系包。Quill 的語系要開發者自己建置(維護一份字典、管理 DOM)。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be8606ffae98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js 範例(3)-Two-floors導覽]]></title>
            <link>https://jacychu.medium.com/three-js-%E7%AF%84%E4%BE%8B-3-two-floors%E5%B0%8E%E8%A6%BD-99c193fbcd6f?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c193fbcd6f</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 05:57:27 GMT</pubDate>
            <atom:updated>2025-08-25T06:37:52.260Z</atom:updated>
            <content:encoded><![CDATA[<h4>從單樓層到雙樓層：樓層切換、碰撞偵測、標註系統與小地圖的進化</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgD7qfgRiQy6VNvbWnt5yQ.png" /></figure><p>📝 回顧章節：<a href="https://jacychu.medium.com/three-js-%E7%AF%84%E4%BE%8B-2-inspect-server-room-497be7d9c4c8">Three.js 範例(2)-Inspect-server-room</a></p><p>✨ 完整程式碼：<a href="https://github.com/jacychutw/threejs-inspect-server-room-second-floor">https://github.com/jacychutw/threejs-inspect-server-room-second-floor</a></p><p>🕹 實際操作：<a href="https://jacychutw.github.io/threejs-inspect-server-room-second-floor/">https://jacychutw.github.io/threejs-inspect-server-room-second-floor/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-rw2RYMI6Gll93kMHHXow.png" /><figcaption>1F</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDx6MUOrpMFqRStkNcIN7A.png" /><figcaption>2F</figcaption></figure><h4>✨ <strong>功能特色</strong></h4><p>🏢 雙樓層切換：支援 1F 與 2F 模型，攝影機位置跟隨樓層調整<br> 🎮 第一人稱移動：鍵盤／螢幕按鈕控制前進後退、旋轉、抬頭低頭<br> 🛑 碰撞偵測：限制走出邊界，避免穿牆<br> 🏷 標註系統：標籤跟著樓層顯示，支援新增、編輯、刪除<br> 👀 遮擋判斷：標籤被物件擋住時自動隱藏<br> 🗺 小地圖 (Minimap)：</p><ul><li>1F 保留 server，不會誤判為天花</li><li>2F 厚天花會在小地圖用 clipping plane 切掉，避免遮住房間</li></ul><h4>1. Imports &amp; 場景初始化</h4><pre>import * as THREE from &#39;https://esm.sh/three@0.164.1&#39;;<br>import { GLTFLoader } from &#39;https://esm.sh/three@0.164.1/examples/jsm/loaders/GLTFLoader.js&#39;;<br>import { CSS2DRenderer, CSS2DObject } from &#39;https://esm.sh/three@0.164.1/examples/jsm/renderers/CSS2DRenderer.js&#39;;<br><br>const scene = new THREE.Scene();<br>const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 1000);<br>camera.rotation.order = &#39;YXZ&#39;;<br><br>const renderer = new THREE.WebGLRenderer({ antialias: true });<br>renderer.setSize(innerWidth, innerHeight);<br>renderer.toneMapping = THREE.ACESFilmicToneMapping;<br>renderer.toneMappingExposure = 1.4;<br>renderer.outputColorSpace = THREE.SRGBColorSpace;</pre><ul><li>與前一篇一致：建立 Scene、Camera、Renderer。</li><li>加入 CSS2DRenderer 處理標註 (tag)。</li></ul><h4>2. 狀態管理與共用邏輯</h4><p>與前一篇幾乎相同：</p><ul><li>floors[]：存每層樓的模型、碰撞清單、天花候選等。</li><li>activeFloorIdx：當前樓層索引。</li><li>tags[]：每個標註的 dot 與 card。</li><li>Raycaster：射線檢測物件。</li><li>updateTagOcclusion()：更新標註是否被擋住。</li></ul><h4>3. 載入雙樓層模型</h4><p>樓層glb模型可以從下方下載：</p><p>(1F)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsketchfab.com%2Fmodels%2F57a480597a20476f9f303fda4a089f86%2Fembed&amp;display_name=Sketchfab&amp;url=https%3A%2F%2Fsketchfab.com%2F3d-models%2Fserver-room-57a480597a20476f9f303fda4a089f86&amp;image=https%3A%2F%2Fmedia.sketchfab.com%2Fmodels%2F57a480597a20476f9f303fda4a089f86%2Fthumbnails%2F93a0edf53218497586decde756adcdfc%2Fa0b7775b2c0f408ab605385e67867d86.jpeg&amp;type=text%2Fhtml&amp;schema=sketchfab" width="640" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/87123ff20ad50653cc88d6231c5938b7/href">https://medium.com/media/87123ff20ad50653cc88d6231c5938b7/href</a></iframe><p>(2F)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsketchfab.com%2Fmodels%2F0f0ff5edb3f8435b87d1c62eda9bc684%2Fembed&amp;display_name=Sketchfab&amp;url=https%3A%2F%2Fsketchfab.com%2F3d-models%2Fa-designer-meeting-room-0f0ff5edb3f8435b87d1c62eda9bc684&amp;image=https%3A%2F%2Fmedia.sketchfab.com%2Fmodels%2F0f0ff5edb3f8435b87d1c62eda9bc684%2Fthumbnails%2F52df2ba61ff84a23980f7adf27f47301%2F50ca7525e3fc4333919ac71faa69229f.jpeg&amp;type=text%2Fhtml&amp;schema=sketchfab" width="640" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d21eafd9122e11b17374ebfd8d7a75/href">https://medium.com/media/63d21eafd9122e11b17374ebfd8d7a75/href</a></iframe><pre>// ===== 載入兩層 =====<br>const loader = new GLTFLoader();<br>const EYE_HEIGHT = 1.6;<br><br>// 1F：server_room.glb<br>loader.load(&#39;models/server_room.glb&#39;, (gltf) =&gt; {<br>  const base = gltf.scene;<br><br>  // 1) 以包圍盒抓中心點，將模型平移，讓該樓層的 (0,0,0) 位於幾何中心<br>  const box = new THREE.Box3().setFromObject(base);<br>  const c = new THREE.Vector3(); <br>  box.getCenter(c);           // c = 模型中心點（世界座標）<br>  base.position.sub(c);       // 整體往反方向移，使中心落在世界原點<br><br>  // 2) 重新計算移動後的包圍盒與尺寸（因為剛剛改了 transform）<br>  box.setFromObject(base);<br>  const sceneSize = new THREE.Vector3(); <br>  box.getSize(sceneSize);     // sceneSize = (寬x, 高y, 深z)<br><br>  // 3) 1F 的地板高度 floorY（樓層底部），若中心在 0，高度為 H，底部 ≈ -H/2<br>  const floorY = -sceneSize.y / 2;<br><br>  // 4) 用統一的樓層建構器抽出：可互動物件、碰撞、天花候選、可走範圍等<br>  const f1 = buildFloorFrom(base, floorY, sceneSize, /*floorIdx=*/0);<br>  floors[0] = f1;<br>  f1.group.visible = false;   // 先隱藏，由切樓函式決定可見性<br>  scene.add(f1.group);<br><br>  // 5) 第一次載入完成時的初始化（只做一次）<br>  if (activeFloorIdx === -1) {<br>    activeFloorIdx = 0;<br>    camera.position.set(0, f1.floorY + EYE_HEIGHT, -1.5); // 眼睛高度 ≈ 地板 + 1.6m<br>    updateFloorVisibility();                               // 僅顯示 1F<br>    initMinimap(f1.sceneSize, f1.floorY);                  // 以 1F 尺寸初始化小地圖<br>  }<br>});<br><br>// 2F：meeting_room.glb<br>loader.load(&#39;models/meeting_room.glb&#39;, (gltf) =&gt; {<br>  const base = gltf.scene;<br><br>  // 1) 同樣流程：中心歸零 + 重新量測<br>  const box = new THREE.Box3().setFromObject(base);<br>  const c = new THREE.Vector3(); box.getCenter(c); base.position.sub(c);<br>  box.setFromObject(base);<br>  const sceneSize = new THREE.Vector3(); box.getSize(sceneSize);<br><br>  // 2) 疊到 1F 上方（留 0.4m 縫）<br>  const gap = 0.4;<br><br>  // 若 1F 尚未載入也不會爆（fallback 為 0）；通常 1F 先回來<br>  const f2FloorY = floors[0] <br>    ? floors[0].floorY + floors[0].sceneSize.y + gap  // 1F 地板 + 1F 高度 + 縫隙 = 2F 地板高度<br>    : 0;<br><br>  // 把整個 2F 模型往上抬到正確高度（因為我們先把中心歸零了，現在要放到目標樓層的 Y）<br>  base.position.y += (floors[0] ? floors[0].sceneSize.y + gap : 0);<br><br>  // 3) 建立 2F 資料<br>  const f2 = buildFloorFrom(base, f2FloorY, sceneSize, /*floorIdx=*/1);<br>  floors[1] = f2;<br>  f2.group.visible = false;<br>  scene.add(f2.group);<br>});</pre><h4>4. 建立樓層 buildFloorFrom()</h4><p>核心差異在「判斷天花板 (roofCandidates) 的規則」：</p><h4>1F — 保守策略</h4><p>避免把 server rack 誤判為天花，所以規則較嚴格：</p><ul><li>名稱包含 roof|ceiling|lamp|天花 等才算</li><li>薄而扁的物件</li><li>面積夠大 + 接近天花高度</li></ul><h4>2F — 粗暴策略</h4><p>只要物件的頂部幾乎貼近天花板 (maxY ≈ ceilY)，就收進 roofCandidates。</p><pre>if (floorIdx === 1) {<br>  // 2F：厚天花 → 任何「頂面幾乎貼到天花」的物件，整塊收進 minimap 天花清單<br>  if (wb.max.y &gt;= ceilY - CEIL_NEAR_EPS) {<br>    roofCandidates.push(o);<br>  }<br>} else {<br>  // 1F：只把薄而扁、或名稱明顯是天花/燈具的收進清單；避免 server 被藏<br>  const isByName = /(roof|ceiling|light|lamp|panel|fixture|grid|duct|vent|beam|led|天花|吊頂|燈)/i.test(nameStr) &amp;&amp; !isServerLike;<br>  const isThinWide = (h &lt;= THIN_H) &amp;&amp; ((Math.max(w, d) / Math.max(h, 1e-3)) &gt;= WIDE_RATIO);<br>  const roomArea = Math.max(1e-3, sceneSize.x * sceneSize.z);<br>  const isLargeCover = (w * d) / roomArea &gt;= LARGE_COVER_RATIO;<br>  const isNearCeiling = (wb.max.y &gt;= ceilY - CEIL_NEAR_EPS);<br><br>  if ((isByName) || (isNearCeiling &amp;&amp; (isThinWide || (isLargeCover &amp;&amp; h &lt;= THIN_H * 1.5)))) {<br>    roofCandidates.push(o);<br>  }<br>}</pre><h4>5. 樓層切換</h4><pre>function switchFloor(idx) {<br>  if (!floors[idx]) return;<br>  activeFloorIdx = idx;<br>  camera.position.y = floors[idx].floorY + EYE_HEIGHT;<br>  updateFloorVisibility();<br>}</pre><ul><li>KeyZ 切換到 1F，KeyX 切換到 2F</li><li>同時更新 minimap 標籤顯示 MAP · 1F / MAP · 2F</li></ul><h4>6. Minimap 小地圖</h4><p>小地圖採 OrthographicCamera（正交相機）+ 透明 WebGLRenderer 疊在 HUD 上顯示。</p><p>核心目標：</p><ul><li>跟著樓層切換：只看當前樓層（避免兩層重疊影響閱讀）。</li><li>玩家朝向可視化：每層有獨立玩家箭頭（1F 藍、2F 橘），只顯示當前樓層那一支。</li><li>2F 厚天花不擋視線：只在小地圖用 clipping plane「切掉」2F 天花的上半部。</li></ul><pre>function renderMinimap() {<br>  if (!miniRenderer || !miniCam || !floors.length) return;<br><br>  // 目前樓層<br>  const cur = floors[activeFloorIdx] ?? floors[0];<br>  if (!cur) return;<br><br>  // 1) 依當前樓層大小調整視錐<br>  const halfW = (cur.sceneSize.x * 0.5) * MINIMAP_SCALE;<br>  const halfH = (cur.sceneSize.z * 0.5) * MINIMAP_SCALE;<br>  if (miniCam.left !== -halfW || miniCam.right !== halfW ||<br>    miniCam.top !== halfH || miniCam.bottom !== -halfH) {<br>    miniCam.left = -halfW; miniCam.right = halfW;<br>    miniCam.top = halfH; miniCam.bottom = -halfH;<br>    miniCam.updateProjectionMatrix();<br>  }<br>  // 讓小地圖俯視目前樓層<br>  miniCam.lookAt(new THREE.Vector3(0, cur.floorY, 1));<br><br>  // 2) 各樓層各自的玩家箭頭（1F 藍、2F 橘），且只顯示當前樓層<br>  for (let i = 0; i &lt; 2; i++) {<br>    if (!playerMarkers[i] &amp;&amp; floors[i]) {<br>      playerMarkers[i] = makePlayerMarker(i === 0 ? 0x0080ff : 0xff8c00);<br>    }<br>    const m = playerMarkers[i];<br>    if (!m || !floors[i]) continue;<br><br>    const baseY = floors[i].floorY;<br>    m.position.set(camera.position.x, baseY + 0.05, camera.position.z);<br>    m.rotation.z = -camera.rotation.y;<br>    m.visible = (i === activeFloorIdx);<br>  }<br><br>  // 3) 暫時隱藏非當前樓層<br>  const prev = new Map();<br>  floors.forEach((f, i) =&gt; {<br>    if (i !== activeFloorIdx &amp;&amp; f?.group) { prev.set(f.group, f.group.visible); f.group.visible = false; }<br>  });<br><br>  // 4) 2F 厚天花用 clipping plane 切掉（只在小地圖）<br>  if (activeFloorIdx === 1) {<br>    // 如果在 2F，為了避免天花板擋住視線，用 clipping plane 把 cutY 以上的部分切掉<br>    const cutY = cur.floorY + MINIMAP_CLIP_HEIGHT_2F;<br>    miniRenderer.localClippingEnabled = true;<br>    miniRenderer.clippingPlanes = [new THREE.Plane(new THREE.Vector3(0, -1, 0), cutY)];<br>  } else {<br>    miniRenderer.clippingPlanes = [];<br>  }<br><br>  // 5) （可選）把偵測到的天花/燈具暫時關掉<br>  for (const m of (cur.roofCandidates ?? [])) { prev.set(m, m.visible); m.visible = false; }<br><br>  // 6) 渲染小地圖<br>  miniRenderer.render(scene, miniCam);<br><br>  // 7) 還原狀態<br>  for (const [obj, vis] of prev) obj.visible = vis;<br>  miniRenderer.clippingPlanes = [];<br>}</pre><h4>7. 互動控制</h4><p>與前一篇相同：</p><ul><li>WASD / 方向鍵：移動與旋轉</li><li>Q / E：抬頭 / 低頭</li><li>HUD 上的按鈕支援滑鼠/觸控</li><li>移動邊界與碰撞檢查，避免穿牆</li></ul><h4>8. Shift 衝刺 (Sprint) 功能</h4><pre>let sprint = false; // Shift 衝刺<br><br><br>document.addEventListener(&#39;keydown&#39;, e =&gt; {<br>  if (e.code === &#39;ShiftLeft&#39; || e.code === &#39;ShiftRight&#39;) sprint = true;<br>});<br>document.addEventListener(&#39;keyup&#39;, e =&gt; {<br>  if (e.code === &#39;ShiftLeft&#39; || e.code === &#39;ShiftRight&#39;) sprint = false;<br>});<br><br><br>function updateMovement(){<br>  // ...<br>  const elapsed = (now - moveStartTime) / 1000;<br>  const speedMul = sprint ? 2.6 : 1.0; // 衝刺倍率<br>  if (elapsed &lt;= 2) {<br>    if (moveForward) velocity.addScaledVector(forward, speed * speedMul * dt);<br>    if (moveBackward) velocity.addScaledVector(backward, speed * speedMul * dt);<br>  } else {<br>    moveInProgress = false;<br>  }<br>  // ...<br>}<br></pre><ul><li>玩家按住 Shift 時移動速度提升（跑步 / 衝刺效果）</li><li>用 sprinting 控管變數狀態，決定按 Shift → 速度加倍，放手 → 速度正常</li></ul><h4>9. 標註系統</h4><p>同前一篇：</p><ul><li>點擊場景 → 新增標註</li><li>點擊 dot → 展開卡片，可編輯/刪除</li><li>標註只顯示在當前樓層 (floorIdx 綁定)</li></ul><h4>10. local storage暫時儲存標註</h4><pre>const STORAGE_KEY = &#39;twofloors_tags_v1&#39;;<br><br>// 存所有標註<br>function saveTags() {<br>  try {<br>    const data = tags.map(t =&gt; ({<br>      floorIdx: t.floorIdx,<br>      // dotObj 直接掛在 scene 上，所以 position 是世界座標，存起來即可<br>      pos: t.dotObj.position.toArray(),<br>      title: t.cardObj.element.querySelector(&#39;strong&#39;)?.innerText || &#39;標註&#39;,<br>      html: t.cardObj.element.querySelector(&#39;.body&#39;)?.innerHTML || &#39;&#39;<br>    }));<br>    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));<br>  } catch (e) {<br>    console.warn(&#39;saveTags failed:&#39;, e);<br>  }<br>}<br><br>// 從 localStorage 還原<br>function loadTags() {<br>  try {<br>    const raw = localStorage.getItem(STORAGE_KEY);<br>    if (!raw) return;<br>    const data = JSON.parse(raw);<br>    const prev = activeFloorIdx;<br><br>    for (const item of data) {<br>      const { floorIdx = 0, pos = [0, 0, 0], title = &#39;標註&#39;, html = &#39;&#39; } = item || {};<br>      // 暫切樓層 → addTag 會把 floorIdx 設成 activeFloorIdx<br>      activeFloorIdx = floorIdx;<br>      addTag(new THREE.Vector3().fromArray(pos), title, html);<br>    }<br><br>    activeFloorIdx = prev;<br>    updateFloorVisibility();<br>  } catch (e) {<br>    console.warn(&#39;loadTags failed:&#39;, e);<br>  }<br>}</pre><ul><li>使用者在場景中點擊新增標註後，會被儲存在 <strong>LocalStorage</strong>（瀏覽器本地）。</li><li>重新整理頁面後可以還原標註。</li><li>收集目前 tags 陣列中的資料，還原從 LocalStorage 取出 JSON。</li></ul><h4>11. 結論</h4><p>這一篇在 Inspect Server Room 的基礎上，新增了：</p><ol><li>多樓層切換（1F/2F）</li><li>不同樓層的天花判定邏輯（保守 vs 粗暴）</li><li>Minimap 裁切天花板，避免視覺被厚天花遮擋</li></ol><p>實際效果：</p><ul><li>1F → server 保持可見</li><li>2F → 厚天花在小地圖被切掉，房間空間更清楚</li></ul><p>由於 2F glb圖檔檔案本身極大，所以用網頁開啟需等候一下，且用手機開啟因 2F 圖檔過大，無法正常顯示。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c193fbcd6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js 範例(2)-Inspect-server-room]]></title>
            <link>https://jacychu.medium.com/three-js-%E7%AF%84%E4%BE%8B-2-inspect-server-room-497be7d9c4c8?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/497be7d9c4c8</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 08:46:05 GMT</pubDate>
            <atom:updated>2025-08-14T08:46:05.562Z</atom:updated>
            <content:encoded><![CDATA[<h4>FPS 視角導覽＋即時標註系統：點哪標哪、被擋即隱藏，體驗真實不穿牆</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aw9k5pIEO4mwfXjgDO31QQ.png" /></figure><p>✨ 完整程式碼：<a href="https://github.com/jacychutw/threejs-inspect-server-room">https://github.com/jacychutw/threejs-inspect-server-room</a></p><p>🕹 實際操作：<a href="https://jacychutw.github.io/threejs-inspect-server-room/">https://jacychutw.github.io/threejs-inspect-server-room/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yw5-owNnonyUEvGNoL3TQw.png" /></figure><h3>✨ 功能特色</h3><ul><li>🎮 第一人稱移動：鍵盤 / 螢幕按鈕控制移動、旋轉、抬頭低頭</li><li>🛑 碰撞偵測：不可穿牆，模擬真實移動體驗</li><li>🏷 標註系統：點擊物件新增標籤與文字說明</li><li>👀 遮擋判斷：標籤被物件擋住時自動隱藏</li><li>🌐 Web 部署：可直接使用 GitHub Pages 預覽</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*wXRuCY8S0y6vwbZx-SsLCQ.png" /></figure><p>以下是程式碼由上而且分功能解釋</p><h3>1) Imports &amp; 場景</h3><pre>import * as THREE from &#39;https://esm.sh/three@0.164.1&#39;;<br>import { GLTFLoader } from &#39;https://esm.sh/three@0.164.1/examples/jsm/loaders/GLTFLoader.js&#39;;<br>import { CSS2DRenderer, CSS2DObject } from &#39;https://esm.sh/three@0.164.1/examples/jsm/renderers/CSS2DRenderer.js&#39;;<br><br>// ===== 場景基礎 =====<br>const scene = new THREE.Scene();<br>scene.background = new THREE.Color(0xeeeeee);<br><br>const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 1000);<br>camera.rotation.order = &#39;YXZ&#39;;<br><br>const renderer = new THREE.WebGLRenderer({ antialias: true });<br>renderer.setSize(innerWidth, innerHeight);<br>renderer.toneMapping = THREE.ACESFilmicToneMapping; // 調整亮度跟色調<br>renderer.toneMappingExposure = 1.4;<br>renderer.outputColorSpace = THREE.SRGBColorSpace;<br>document.body.appendChild(renderer.domElement);<br><br>// CSS2D 層（可點）<br>const labelRenderer = new CSS2DRenderer();<br>labelRenderer.setSize(innerWidth, innerHeight);<br>labelRenderer.domElement.style.position = &#39;absolute&#39;;<br>labelRenderer.domElement.style.inset = &#39;0&#39;;<br>labelRenderer.domElement.style.pointerEvents = &#39;auto&#39;;<br>labelRenderer.domElement.style.zIndex = &#39;2&#39;;<br>document.body.appendChild(labelRenderer.domElement);<br><br>// ===== 燈光 =====<br>scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.5));<br>scene.add(new THREE.AmbientLight(0xffffff, 0.8));<br>const dir = new THREE.DirectionalLight(0xffffff, 2.5);<br>dir.position.set(20, 10, 10);<br>scene.add(dir);</pre><ul><li>THREE.PerspectiveCamera(60, aspect, 0.1, 1000)：以人眼視角，近期/遠裁剪面合理。</li><li>camera.rotation.order = &#39;YXZ&#39;：先 yaw 再 pitch，避免萬向節鎖影響（有手動限制 pitch）。第一人稱或自由視角控制（FPS 視角、Google Street View 類型）時幾乎都會用 &#39;YXZ&#39;。</li><li>renderer：開 antialias、ACESFilmicToneMapping + exposure=1.4、sRGBColorSpace—這三個一起會讓 GLB 材質觀感自然。</li><li>CSS2DRenderer 疊在 WebGL 上層、開啟 pointerEvents 以便點擊標籤。</li></ul><h3>2) 全域狀態與常數</h3><pre>// ===== 全域狀態 / 常數 =====<br>const mouseNDC = new THREE.Vector2();  // 標準化裝置座標<br>const pickables = []; // 可被點擊選取的物件清單<br>const tags = []; // 放標記（label）的資料結構方便操作<br><br>// ====== 碰撞檢查（柱子 / server 不穿透）======<br>const colliders = [];                 // 會被視為障礙物的 mesh<br>const PLAYER_RADIUS = 0.30;           // 相機碰撞半徑（可調 0.25~0.4）<br>const RAY_OFFSETS_Y = [0, -0.6, -1.2];// 眼睛、腰、膝 三條射線，提升穩定性<br><br>// ===== Raycaster（點擊放標記）=====<br>const raycaster = new THREE.Raycaster();<br><br>// 專門做遮擋檢查（不要和點擊共用，避免干擾）<br>const occRay = new THREE.Raycaster();<br>const OCC_EPS = 0.04; // 稍微調大，減少貼面誤判</pre><ul><li>把互動物件分成 pickables（用來點擊放標註）與 colliders（用來碰撞）—目前兩者相同集合，清楚直覺。</li><li>碰撞採三條 Y-offset 射線（眼、腰、膝）：RAY_OFFSETS_Y = [0, -0.6, -1.2]，能大幅減少貼邊穿透。</li><li>PLAYER_RADIUS = 0.30：相機當成圓柱 hitbox；之後 willCollide 會利用它。</li><li>Raycaster 用來發射看不見的射線 (Ray)去偵測它碰到哪些物體的工具。</li></ul><h4><strong>設計邏輯：</strong></h4><ul><li>滑鼠點擊 → 更新 mouseNDC → raycaster 檢測 pickables → 新增標籤 → tags.push(label)</li><li>玩家移動 → 從玩家位置發射多條射線（眼睛/腰/膝）檢測 colliders → 如果有撞到則阻止進一步移動</li><li>每幀渲染前 → 用 occRay 從相機位置指向標籤位置 → 判斷中間是否有障礙 → 如果有就隱藏標籤</li></ul><h3>3) 標註系統</h3><pre>// ===== 標註：可見性同步 =====<br>function syncTagVisibility(t) {<br>  // 只要被遮擋，就全部隱藏；沒遮擋時：開卡片→只顯示卡片；關卡片→只顯示圓點<br>  t.dotObj.visible = !t.occluded &amp;&amp; !t.open;<br>  t.cardObj.visible = !t.occluded &amp;&amp; t.open;<br>}<br><br>// ===== 標註：遮擋檢查 =====<br>function updateTagOcclusion() {<br>  if (!colliders.length || !tags.length) return;<br><br>  for (const t of tags) {<br>    // 讀世界座標；保險起見先刷新矩陣<br>    t.dotObj.updateWorldMatrix(true, false);<br>    const worldPos = new THREE.Vector3();<br>    t.dotObj.getWorldPosition(worldPos);<br><br>    const dir = worldPos.clone().sub(camera.position);<br>    const dist = dir.length();<br>    if (dist &lt; 1e-4) {<br>      t.occluded = false;<br>      syncTagVisibility(t);<br>      continue;<br>    }<br>    dir.normalize();<br><br>    occRay.set(camera.position, dir);<br>    occRay.near = 0.001;<br>    occRay.far = Math.max(0, dist - OCC_EPS);<br><br>    const hits = occRay.intersectObjects(colliders, true);<br>    t.occluded = hits.length &gt; 0;<br><br>    syncTagVisibility(t);<br>  }<br>}</pre><h4>syncTagVisibility(t)</h4><ul><li>根據 t.occluded（有無被遮擋）與 t.open（是否展開卡片）來切換：</li><li>遮擋：點與卡都隱藏</li><li>未遮擋：開卡→只顯示卡；關卡→只顯示圓點</li><li><strong>優點</strong>：DOM 顯示策略集中於一處；其他地方只改 open/occluded。</li></ul><h4>updateTagOcclusion()</h4><ul><li>使用獨立 occRay 從相機朝「標註圓點的世界座標」發射，far = dist - OCC_EPS，避免「貼臉」誤判。</li><li>目的是純遮擋檢查，與點擊 ray 分離，互不干擾。</li><li>更新每個 tag 的 occluded 後，呼叫 syncTagVisibility()。</li></ul><pre>// ===== 建立可點標籤 + 內容卡片（用 cardObj.visible 控制顯示）=====<br>function addTag(worldPos, title = &#39;標註&#39;, html = &#39;&#39;) {<br>  // Tag 圓點<br>  const dot = document.createElement(&#39;button&#39;);<br>  dot.className = &#39;label tag-dot&#39;;<br>  dot.title = &#39;查看標註&#39;;<br>  dot.textContent = &#39;i&#39;;<br>  dot.style.cssText =<br>    &#39;width:22px;height:22px;border-radius:50%;&#39; +<br>    &#39;border:2px solid #fff;background:rgba(40,120,255,.95);color:#fff;&#39; +<br>    &#39;font:700 12px/1 system-ui;display:flex;align-items:center;justify-content:center;&#39; +<br>    &#39;box-shadow:0 2px 8px rgba(0,0,0,.35);cursor:pointer;&#39;;<br>  dot.style.zIndex = &#39;1&#39;; // 圓點放低一點<br>  const dotObj = new CSS2DObject(dot);<br>  dotObj.position.copy(worldPos);<br>  scene.add(dotObj);<br><br>  // 內容卡片<br>  const card = document.createElement(&#39;div&#39;);<br>  card.className = &#39;label&#39;;<br>  card.style.cssText =<br>    &#39;min-width:220px;max-width:320px;padding:10px 12px;&#39; +<br>    &#39;background:rgba(0,0,0,.72);color:#fff;border-radius:10px;&#39; +<br>    &#39;font:500 13px/1.45 system-ui;backdrop-filter:blur(4px);&#39; +<br>    &#39;box-shadow:0 10px 24px rgba(0,0,0,.35);&#39;;<br>  card.style.zIndex = &#39;10&#39;; // 卡片永遠在圓點之上<br>  card.innerHTML = `<br>    &lt;div style=&quot;display:flex;justify-content:space-between;align-items:center;gap:8px;&quot;&gt;<br>      &lt;strong&gt;${title}&lt;/strong&gt;<br>      &lt;span style=&quot;display:flex;gap:6px;&quot;&gt;<br>        &lt;button class=&quot;editBtn&quot;   style=&quot;all:unset;cursor:pointer;padding:4px 6px;border-radius:6px;background:rgba(255,255,255,.15)&quot;&gt;編輯&lt;/button&gt;<br>        &lt;button class=&quot;deleteBtn&quot; style=&quot;all:unset;cursor:pointer;padding:4px 6px;border-radius:6px;background:rgba(255,80,80,.25)&quot;&gt;刪除&lt;/button&gt;<br>        &lt;button class=&quot;closeBtn&quot;  style=&quot;all:unset;cursor:pointer;padding:4px 6px;border-radius:6px;background:rgba(255,255,255,.15)&quot;&gt;關閉&lt;/button&gt;<br>      &lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;body&quot; style=&quot;margin-top:6px&quot;&gt;${html}&lt;/div&gt;<br>    `;<br>  const cardObj = new CSS2DObject(card);<br>  // 稍微再往上偏一點，避免重疊<br>  cardObj.position.copy(worldPos).add(new THREE.Vector3(0, 0.3, 0));<br>  cardObj.visible = false;<br>  scene.add(cardObj);<br><br>  // 小工具：統一控制開/關（只改狀態，實際顯示交給 syncTagVisibility）<br>  const rec = { dotObj, cardObj, open: false, occluded: false };<br><br>  const setOpen = (open) =&gt; {<br>    rec.open = open;<br>    syncTagVisibility(rec);<br>  };<br><br>  // ---- 行為 ----<br>  const removeTag = () =&gt; {<br>    scene.remove(dotObj); scene.remove(cardObj);<br>    dot.remove(); card.remove();<br>  };<br><br>  dot.addEventListener(&#39;click&#39;, (ev) =&gt; { ev.stopPropagation(); setOpen(!rec.open); });<br>  card.querySelector(&#39;.closeBtn&#39;)?.addEventListener(&#39;click&#39;, (ev) =&gt; { ev.stopPropagation(); setOpen(false); });<br>  card.querySelector(&#39;.editBtn&#39;)?.addEventListener(&#39;click&#39;, (ev) =&gt; {<br>    ev.stopPropagation();<br>    const body = card.querySelector(&#39;.body&#39;);<br>    const v = prompt(&#39;編輯標註內容：&#39;, body ? body.innerText : &#39;&#39;);<br>    if (v != null) body.innerHTML = String(v).replace(/\n/g, &#39;&lt;br/&gt;&#39;);<br>  });<br>  card.querySelector(&#39;.deleteBtn&#39;)?.addEventListener(&#39;click&#39;, (ev) =&gt; { ev.stopPropagation(); removeTag(); });<br><br>  // ⬇️ 重要：把「style.visibility = hidden/visible」那種 DOM 操作移除，交給 syncTagVisibility<br>  tags.push(rec);<br>  syncTagVisibility(rec);   // 初始狀態：只顯示圓點<br>  return rec;<br>}<br><br>// ===== 收合所有標註卡片 =====<br>function closeAllTags() {<br>  let closed = false;<br>  for (const t of tags) {<br>    if (t.open) {<br>      t.open = false;<br>      syncTagVisibility(t);<br>      closed = true;<br>    }<br>  }<br>  return closed;<br>}</pre><h4>addTag(worldPos, title, html)</h4><ul><li>建兩個 CSS2DObject：一顆「i」圓點（低 z-index）與一個卡片（高 z-index）。</li><li>事件：點圓點會 toggle 開合，卡片內：編輯、刪除、關閉。</li><li>關鍵做法：不直接用 DOM 的 style.visibility 到處改，統一交給 syncTagVisibility 管；狀態集中在 {open, occluded}。</li><li>卡片位置：相對圓點 +Y 0.3，避免重疊。</li><li>回傳 rec 並 push 到 tags，便於之後統一處理。</li></ul><h4>closeAllTags()</h4><ul><li>收起所有打開的卡片，回傳是否有做事（讓 click handler 可「先嘗試收合，不要誤新增」）。</li></ul><h3>4) 載入 GLB（初始化互動空間）</h3><pre>// ===== 載入 GLB =====<br>const loader = new GLTFLoader();<br>let moveBounds = null;<br>loader.load(&#39;models/server_room.glb&#39;, (gltf) =&gt; {<br>  const model = gltf.scene;<br><br>  // 置中<br>  const box = new THREE.Box3().setFromObject(model);<br>  const center = new THREE.Vector3(); box.getCenter(center);<br>  model.position.sub(center);<br>  scene.add(model);<br><br>  // === 算地板高度並把視角設為 1.6 公尺 ===<br>  const size = new THREE.Vector3();<br>  box.getSize(size);<br>  const floorY = -size.y / 2;   // 置中後，地板大約在 -size.y/2<br>  const EYE_HEIGHT = 1.6;       // 160公分<br>  camera.position.set(0, floorY + EYE_HEIGHT, -1.5);<br><br>  // 收集 Mesh 當 pickables + colliders（障礙）<br>  model.traverse(o =&gt; {<br>    if (o.isMesh) {<br>      pickables.push(o);      // 用來打點新增標註<br>      colliders.push(o);      // 當作障礙物以避免穿透<br>      o.updateMatrixWorld(true);<br>    }<br>  });<br><br>  // === 建立可移動方形邊界（縮小一點 margin，避免穿牆）===<br>  const margin = 0.3; // 你可調整 0.2~0.5<br>  const minX = -size.x / 2 + margin;<br>  const maxX = size.x / 2 - margin;<br>  const minZ = -size.z / 2 + margin;<br>  const maxZ = size.z / 2 - margin;<br>  moveBounds = new THREE.Box2(<br>    new THREE.Vector2(minX, minZ),<br>    new THREE.Vector2(maxX, maxZ)<br>  );<br><br>}, undefined, (e) =&gt; console.error(&#39;❌ GLB 載入失敗：&#39;, e));</pre><ul><li>置中：用 Box3().setFromObject(model) 取得 center，整體位移 -center。</li><li>設定「視線高度」：用包盒算地板 floorY = -size.y/2，相機放 floorY + 1.6。</li><li>model.traverse(o.isMesh)：把 GLB 裡的所有網格物件 (Mesh) 收集起來丟進 pickables 與 colliders。</li><li>moveBounds：以包盒建立<strong>略縮</strong>的移動邊界（margin=0.3），避免靠牆時穿模。</li></ul><h3>5) 輸入與控制</h3><pre>// ===== 只有按鈕/鍵盤控制：移動/旋轉/抬頭低頭 =====<br>let moveForward = false, moveBackward = false, rotateLeft = false, rotateRight = false, lookUp = false, lookDown = false;<br>let velocity = new THREE.Vector3();<br>const speed = 2.0, rotationSpeed = 1.5, lookSpeed = 1.0;<br>let moveStartTime = 0, moveInProgress = false;<br><br>document.addEventListener(&#39;keydown&#39;, (e) =&gt; {<br>  if (!moveInProgress) {<br>    switch (e.code) {<br>      case &#39;ArrowUp&#39;: case &#39;KeyW&#39;: moveForward = true; break;<br>      case &#39;ArrowDown&#39;: case &#39;KeyS&#39;: moveBackward = true; break;<br>      case &#39;ArrowLeft&#39;: case &#39;KeyA&#39;: rotateLeft = true; break;<br>      case &#39;ArrowRight&#39;: case &#39;KeyD&#39;: rotateRight = true; break;<br>      case &#39;KeyQ&#39;: lookUp = true; break;<br>      case &#39;KeyE&#39;: lookDown = true; break;<br>    }<br>    moveStartTime = performance.now();<br>    moveInProgress = true;<br>  }<br>});<br>document.addEventListener(&#39;keyup&#39;, (e) =&gt; {<br>  switch (e.code) {<br>    case &#39;ArrowUp&#39;: case &#39;KeyW&#39;: moveForward = false; break;<br>    case &#39;ArrowDown&#39;: case &#39;KeyS&#39;: moveBackward = false; break;<br>    case &#39;ArrowLeft&#39;: case &#39;KeyA&#39;: rotateLeft = false; break;<br>    case &#39;ArrowRight&#39;: case &#39;KeyD&#39;: rotateRight = false; break;<br>    case &#39;KeyQ&#39;: lookUp = false; break;<br>    case &#39;KeyE&#39;: lookDown = false; break;<br>  }<br>});<br><br>function bindHoldButton(id, onDown, onUp) {<br>  const el = document.getElementById(id);<br>  const activate = (e) =&gt; { e.preventDefault(); el.classList.add(&#39;active&#39;); onDown(); };<br>  const deactivate = (e) =&gt; { e &amp;&amp; e.preventDefault(); el.classList.remove(&#39;active&#39;); onUp(); };<br>  el.addEventListener(&#39;mousedown&#39;, activate); addEventListener(&#39;mouseup&#39;, deactivate);<br>  el.addEventListener(&#39;touchstart&#39;, activate, { passive: false });<br>  addEventListener(&#39;touchend&#39;, deactivate, { passive: false });<br>  addEventListener(&#39;touchcancel&#39;, deactivate, { passive: false });<br>  el.addEventListener(&#39;mouseleave&#39;, (e) =&gt; { if (e.buttons === 1) deactivate(e); });<br>}<br>bindHoldButton(&#39;btnForward&#39;, () =&gt; { moveForward = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { moveForward = false; moveInProgress = false; });<br>bindHoldButton(&#39;btnBackward&#39;, () =&gt; { moveBackward = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { moveBackward = false; moveInProgress = false; });<br>bindHoldButton(&#39;btnRotateLeft&#39;, () =&gt; { rotateLeft = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { rotateLeft = false; moveInProgress = false; });<br>bindHoldButton(&#39;btnRotateRight&#39;, () =&gt; { rotateRight = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { rotateRight = false; moveInProgress = false; });<br>bindHoldButton(&#39;btnLookUp&#39;, () =&gt; { lookUp = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { lookUp = false; moveInProgress = false; });<br>bindHoldButton(&#39;btnLookDown&#39;, () =&gt; { lookDown = true; moveStartTime = performance.now(); moveInProgress = true; }, () =&gt; { lookDown = false; moveInProgress = false; });<br><br>let last = performance.now();</pre><ul><li>鍵盤：W/S 前後、A/D 左右旋轉、Q/E 抬頭/低頭；按下時記 moveStartTime，超過 2 秒自動結束連續移動（行動裝置也靠 HUD 按鈕）。</li><li>bindHoldButton：把按下/放開變成布林旗標，並加上按鈕縮放效果。</li></ul><h3>6) 碰撞與移動</h3><pre><br>// ===== 碰撞判斷：本幀位移是否會撞到障礙 =====<br>function willCollide(origin, moveVec) {<br>  const len = moveVec.length();<br>  if (len &lt; 1e-6) return false;<br>  const dir = moveVec.clone().normalize();<br><br>  for (const offY of RAY_OFFSETS_Y) {<br>    const from = new THREE.Vector3(origin.x, origin.y + offY, origin.z);<br>    const ray = new THREE.Raycaster(from, dir, 0, len + PLAYER_RADIUS);<br>    const hits = ray.intersectObjects(colliders, true);<br>    if (hits.length &amp;&amp; hits[0].distance &lt;= len + PLAYER_RADIUS) {<br>      return true; // 撞到了<br>    }<br>  }<br>  return false;<br>}<br><br>function updateMovement() {<br>  const now = performance.now();<br>  const dt = Math.min((now - last) / 1000, 0.1); // 計算兩幀時間差，限制最大0.1秒 避免卡頓<br>  last = now;<br><br>  velocity.set(0, 0, 0); // 每次更新都先歸零速度<br><br>  const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion); // 原指向世界座標的 -Z 軸 改轉成世界座標的前方向<br>  forward.y = 0; forward.normalize(); // 移除垂直分量，保證平地移動<br>  const backward = forward.clone().negate();<br><br>  const elapsed = (now - moveStartTime) / 1000;<br>  if (elapsed &lt;= 2) { // 限制 2 秒內才移動<br>    if (moveForward) velocity.addScaledVector(forward, speed * dt);<br>    if (moveBackward) velocity.addScaledVector(backward, speed * dt);<br>  } else {<br>    moveInProgress = false;<br>  }<br><br>  // 嘗試移動前先做碰撞檢查（撞到就不移動）<br>  if (!willCollide(camera.position, velocity)) {<br>    camera.position.add(velocity);<br>  }<br><br>  // === 仍保留方形範圍限制（限制X/Z不能超過範圍，避免走出模型外）===<br>  if (moveBounds) {<br>    camera.position.x = Math.min(moveBounds.max.x, Math.max(moveBounds.min.x, camera.position.x));<br>    camera.position.z = Math.min(moveBounds.max.y, Math.max(moveBounds.min.y, camera.position.z));<br>  }<br><br>  if (rotateLeft) camera.rotation.y += rotationSpeed * dt;<br>  if (rotateRight) camera.rotation.y -= rotationSpeed * dt;<br><br>  if (lookUp) { camera.rotation.x += lookSpeed * dt; if (camera.rotation.x &gt; Math.PI / 2) camera.rotation.x = Math.PI / 2; }<br>  if (lookDown) { camera.rotation.x -= lookSpeed * dt; if (camera.rotation.x &lt; -Math.PI / 2) camera.rotation.x = -Math.PI / 2; }<br>  camera.rotation.z = 0; // 不傾斜<br>}</pre><h4>willCollide(origin, moveVec)</h4><ul><li>將本幀位移做歸一化方向，對三個 offY 位置各射一條 ray。</li><li>若最近 hit 距離 &lt;= len + PLAYER_RADIUS 就視為會撞。</li><li>這是「預測本幀前進是否撞」的做法，簡單又有效。</li></ul><h4>updateMovement()</h4><ul><li>計 dt（上限 0.1 避掉跳幀）、根據鍵位組合計 velocity。</li><li>前向取 camera.quaternion 的 -Z，再投影到地面（y = 0），避免抬頭低頭影響平面移動。</li><li>先調用 willCollide，通過才 position += velocity。</li><li>套用 moveBounds 做最終夾限（兩層保護：碰撞 + 邊界）。</li><li>旋轉與俯仰：rotation.y 左右，rotation.x 上下並夾在 [-π/2, π/2]。</li></ul><h3>7) 點擊畫面（新增標註 / 先收合）</h3><pre>// ===== 點擊畫面：新增標註 =====<br>document.addEventListener(&#39;click&#39;, (e) =&gt; {<br>  const inLabel = !!e.target.closest(&#39;.label&#39;); // 點在標籤或卡片上<br>  const inHUD = !!e.target.closest(&#39;.hud&#39;);   // 點在 HUD 上<br><br>  // 不是點在標籤上：先嘗試收起所有卡片<br>  if (!inLabel) {<br>    const didClose = closeAllTags();<br>    if (didClose) return; // ← 這次點擊只做「收起」，不要新增標註<br>  }<br><br>  // 點在 HUD 或標籤上就不新增標註<br>  if (inHUD || inLabel) return;<br><br>  // 以下才是「新增標註」<br>  const rect = renderer.domElement.getBoundingClientRect();<br>  mouseNDC.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;<br>  mouseNDC.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;<br><br>  raycaster.setFromCamera(mouseNDC, camera);<br>  const hits = raycaster.intersectObjects(pickables, true); // 檢查這條射線是否擊中任何可標註的物件<br>  if (!hits.length) return;<br><br>  const hit = hits[0]; // 擊中的世界座標<br>  const pos = hit.point.clone().add(hit.face?.normal?.clone().multiplyScalar(0.02) || new THREE.Vector3());<br><br>  const text = prompt(&#39;輸入標註內容：&#39;, &#39;這裡是我的標註&#39;);<br>  if (text === null) return; // 取消就不新增<br>  const content = (text.trim() === &#39;&#39; ? &#39;（未命名標註）&#39; : text).replace(/\n/g, &#39;&lt;br/&gt;&#39;);<br>  addTag(pos, &#39;標註&#39;, content);<br>});</pre><ul><li>先判斷是否點在 .label 或 .hud：如果不是點標籤，先 closeAllTags()；有收合就 return（這次點擊只做收合，不新增）。點在 HUD 或標籤上則不新增。</li><li>NDC 把「滑鼠在畫布上的像素位置」轉換成「-1 到 1 的相對座標系」，<br> 讓 Three.js / WebGL 在不同螢幕大小下都能正確計算射線方向。</li><li>真的要新增時：用 raycaster.setFromCamera(mouseNDC, camera) 射向 pickables，取最前 hit.point，再沿法線微移 0.02，避免 z-fighting。</li><li>prompt() 取得內容→addTag 建立。</li></ul><h3>8) resize 與主迴圈</h3><pre>// ===== 視窗縮放 =====<br>addEventListener(&#39;resize&#39;, () =&gt; {<br>  camera.aspect = innerWidth / innerHeight;  // 更新相機長寬比<br>  camera.updateProjectionMatrix();  // 重新計算投影矩陣<br>  renderer.setSize(innerWidth, innerHeight); // WebGLRenderer 跟著縮放<br>  labelRenderer.setSize(innerWidth, innerHeight); // CSS2DRenderer 跟著縮放<br>});<br><br>// ===== 迴圈 =====<br>function animate() {<br>  requestAnimationFrame(animate); // 註冊下一幀（由瀏覽器排程）<br>  updateMovement(); // 處理輸入、移動、碰撞、邊界<br>  updateTagOcclusion(); // 處理標籤遮擋（可見性切換）<br>  renderer.render(scene, camera); // 繪製 3D<br>  labelRenderer.render(scene, camera); // 繪製 2D 標籤（覆蓋在上層）<br>}<br>animate();</pre><ul><li>resize：更新相機投影矩陣、兩個 renderer 的尺寸。</li><li>function animate()：主迴圈處理移動跟標籤遮擋還有3D影像跟2D標籤</li></ul><h3>小結</h3><p>這個專案把「走進 3D 機房、所見即標」變成一個可直接部署的網頁體驗。核心做法是把互動拆成清楚的模組：</p><ul><li>導覽與碰撞：第一人稱移動 + 三段高度射線（眼/腰/膝）做預判，不會穿牆；再以方形邊界做第二層保護。</li><li>標註系統：點擊即建「圓點＋卡片」兩個 CSS2D 物件，統一用 syncTagVisibility(open, occluded) 控制顯示邏輯；另設獨立射線 occRay 做遮擋判斷，互不干擾。</li><li>視覺與可用性：ACES Filmic + sRGB 的輸出讓 GLB 呈現更自然；Label 層開啟 pointerEvents 方便操作；Resize 時同步兩個 renderer。</li></ul><p>🪃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=497be7d9c4c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js 範例(1)：使用 Skybox、模型載入與平滑相機移動]]></title>
            <link>https://jacychu.medium.com/three-js-%E7%AF%84%E4%BE%8B-1-%E4%BD%BF%E7%94%A8-skybox-%E6%A8%A1%E5%9E%8B%E8%BC%89%E5%85%A5%E8%88%87%E5%B9%B3%E6%BB%91%E7%9B%B8%E6%A9%9F%E7%A7%BB%E5%8B%95-1b86460e3a80?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b86460e3a80</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 08:57:42 GMT</pubDate>
            <atom:updated>2025-08-12T08:57:42.607Z</atom:updated>
            <content:encoded><![CDATA[<h4>逐行解析 index.html，從天空盒與水面材質到方向光、半球光、GLTF 模型與按鈕控制相機漫遊</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG2tFIG-63d1uiu9VAjGQA.png" /></figure><p>身在一個巨大環境裡，只需要輕鬆漫遊～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iDoDGg21U54YEXSLshGdQ.gif" /></figure><h4>檔案結構</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*HoX1ayHh1CxC1CmOV92XtA.png" /></figure><p>完整index.html檔案</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/691ebb225551b212ef342b537d098ebe/href">https://medium.com/media/691ebb225551b212ef342b537d098ebe/href</a></iframe><p>鴨子檔案可從這邊下載：</p><p><a href="https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck">https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck</a></p><p>negx, negy, negz, posx, posy, posz 檔案可從此下載：</p><p><a href="https://opengameart.org/content/field-skyboxes">Field skyboxes</a></p><p>以下是 index.html 詳細說明</p><h3>詳細說明：</h3><pre>const scene = new THREE.Scene();<br>const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);<br>camera.position.set(0, 1.6, 5); // 設定相機在世界座標系的位置<br><br>const renderer = new THREE.WebGLRenderer({ antialias: true });<br>renderer.setSize(window.innerWidth, window.innerHeight);<br>document.body.appendChild(renderer.domElement);<br><br>const controls = new OrbitControls(camera, renderer.domElement);<br>controls.target.set(0, 1.6, 4); // 初始觀看方向 <br>controls.update();</pre><p>camera.position.set(0, 1.6, 5); 設定相機在世界座標系的位置controls.target.set(0, 1.6, 4); 初始觀看方向</p><p>三個參數分別是 <strong>X, Y, Z</strong>：</p><ul><li>0 → 左右位置（正數往右，負數往左）</li><li>1.6 → 高度（通常 1.6m 模擬人眼高度）</li><li>5 → 前後位置（正數遠離原點，負數靠近原點）</li></ul><p>這樣代表目標點就在相機前方 Z 軸方向 1 公尺的位置（因為相機在 z=5，看 z=4）</p><pre>// Skybox<br>const loaderCube = new THREE.CubeTextureLoader();<br>const skyTexture = loaderCube.load([<br>  &#39;models/posx.jpg&#39;, &#39;models/negx.jpg&#39;,<br>  &#39;models/posy.jpg&#39;, &#39;models/negy.jpg&#39;,<br>  &#39;models/posz.jpg&#39;, &#39;models/negz.jpg&#39;,<br>]);<br>scene.background = skyTexture;</pre><p>THREE.CubeTextureLoader() 是 three.js 專門用來載入 <strong>立方體貼圖（cube map）</strong> 的載入器。</p><p>cube map 是由 <strong>6 張圖片</strong>組成，分別對應一個立方體的 6 個面：</p><p>+X（右）−X（左）+Y（上）−Y（下）+Z（前）−Z（後）</p><p>檔案可從此下載：</p><p><a href="https://opengameart.org/content/field-skyboxes">Field skyboxes</a></p><p>scene.background 可以接收：</p><ul><li>單張 2D 貼圖（Texture）</li><li>立方體貼圖（CubeTexture）</li><li>單一顏色（Color）</li></ul><p>這裡指定 CubeTexture，three.js 就會自動把它當作 背景天空盒：背景固定在無限遠，不會被相機位移影響。當相機旋轉時，背景會跟著旋轉，營造出環繞四周的感覺。</p><h4>Skybox 的好處</h4><ul><li><strong>高性能</strong>：相比真的放一個超大的球體/立方體包住場景，Skybox 不需要額外的幾何計算，純粹背景渲染。</li><li><strong>沉浸感</strong>：模擬真實天空、遠山、城市天際線等。</li></ul><pre>// Water plane<br>const waterMaterial = new THREE.MeshPhysicalMaterial({<br>  color: 0x3366ff,         // 水的基礎顏色（深藍色）<br>  transmission: 0.9,       // 光線透射率（0=不透光, 1=完全透光）<br>  thickness: 2.0,          // 材質的「厚度」，影響折射效果<br>  roughness: 0.1,          // 表面粗糙度（越低越光滑，反射越清晰）<br>  metalness: 0.0,          // 金屬感（0=非金屬，水=0）<br>  envMap: skyTexture,      // 使用天空盒作為反射環境<br>  envMapIntensity: 1.0,    // 環境反射強度<br>  transparent: true,       // 開啟透明度支持（否則 opacity 不生效）<br>  opacity: 1.0,            // 不完全透明（1.0=不透明, 0.0=完全透明）<br>  ior: 1.33,               // 折射率（1.33 是水的折射率）<br>  reflectivity: 0.3,       // 反射強度（主要用在非 PBR 模式）<br>  side: THREE.DoubleSide,  // 雙面渲染（避免從背面看不見水面）<br>});<br><br>const pond = new THREE.Mesh(<br>  new THREE.PlaneGeometry(100, 100),<br>  waterMaterial<br>);<br>pond.rotation.x = -Math.PI / 2;<br>pond.position.y = 0;<br>scene.add(pond);</pre><p>MeshPhysicalMaterial 是 three.js 中最「物理正確」的 PBR 材質，支援光線透射、折射率、厚度、粗糙度等。適合用來做玻璃、水、寶石等透明物體。</p><p>new THREE.PlaneGeometry(100,100)</p><ul><li>建一個 100×100 的平面。</li><li>因為水面應該是「水平」的，所以下一步會把它旋轉。</li></ul><pre>pond.rotation.x = -Math.PI / 2; // 將平面從直立轉成水平<br>pond.position.y = 0;            // 高度設在 y=0（世界地面）</pre><pre>const light = new THREE.DirectionalLight(0xffffff, 1);<br>light.position.set(5, 10, 5);<br>scene.add(light);<br><br>scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 2));</pre><h4>方向光 DirectionalLight</h4><ul><li>模擬太陽光或遠距離光源：光線平行照射，不會因為距離衰減。</li><li>整個場景的光線方向一致，就像太陽在天空某處。</li><li>0xffffff → 光的顏色（白光）。1 → 光的強度（數字越大越亮）。</li><li>position.set(5, 10, 5) → 光線方向其實是「從光源位置指向場景中心」。</li><li>在 three.js 中，方向光的位置 + target 決定光線方向，預設 target 在 (0, 0, 0)。現在設定的 (5, 10, 5) 代表光線是從右上方斜射到場景中央。</li></ul><h4>半球光 HemisphereLight</h4><ul><li>模擬天空光與地面反射光：上半部（skyColor）顏色：0xffffff（白色）下半部（groundColor）顏色：0x444444（深灰色）強度：2（比 DirectionalLight 還亮一點）</li><li>半球光沒有方向、沒有陰影，是一種「全域環境光」，讓物體的暗部不會完全黑掉。</li><li>非常適合跟方向光搭配：方向光 → 提供主要光影 半球光 → 填補陰影區域的亮度，讓暗部也能看到細節</li></ul><h4>為什麼要同時用兩種光？</h4><ul><li><strong>單用 DirectionalLight</strong>：亮部很亮，但背光面太暗，對比強烈。</li><li><strong>加 HemisphereLight</strong>：背光面會有環境亮度，看起來柔和自然。</li></ul><pre>// Duck model<br>let duckModel;<br>const loader = new GLTFLoader();<br>loader.load(&#39;models/Duck.gltf&#39;, (gltf) =&gt; {<br>  duckModel = gltf.scene;<br>  duckModel.position.set(0, 0.1, 0);<br>  scene.add(duckModel);<br>});</pre><p>duckModel.position.set(0, 0.1, 0) → 把小鴨放到 X=0, Y=0.1, Z=0 的位置（稍微抬高，避免埋進地面）。</p><p>🚪 可參考文章：<a href="https://jacychu.medium.com/three-js-5-5-%E5%B0%8E%E5%85%A5-3d-%E6%A8%A1%E5%9E%8B-gltf-glb-a65cee644c0b">Three.js (5/5)導入 3D 模型 glTF / GLB</a></p><pre>// Smooth camera movement<br>let targetPosition = camera.position.clone();<br>const moveStep = 2.0;</pre><ul><li>targetPosition存「相機要去的目標位置」。</li><li>一開始複製目前的 camera.position，後面會逐漸 lerp 過去（在 animate() 裡）。</li><li>moveStep每次按按鈕要移動的距離，單位是場景座標單位。</li></ul><h4>相機移動的核心函式</h4><pre>function moveCamera(directionVector) {<br>  targetPosition.add(directionVector);<br>}</pre><ul><li>接收一個「方向向量」，並加到 targetPosition 上。</li><li>注意：這裡不直接改 camera.position，而是改<strong>目標位置</strong>，讓動畫循環 (animate()) 用平滑插值去追隨這個位置，達成「平滑移動」效果</li></ul><pre>document.getElementById(&#39;arrow-up&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  const dir = new THREE.Vector3();<br>  camera.getWorldDirection(dir).normalize();<br>  moveCamera(dir.multiplyScalar(moveStep));<br>});<br><br>document.getElementById(&#39;arrow-down&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  const dir = new THREE.Vector3();<br>  camera.getWorldDirection(dir).normalize().negate();<br>  moveCamera(dir.multiplyScalar(moveStep));<br>});<br><br>document.getElementById(&#39;arrow-left&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  const dir = new THREE.Vector3();<br>  camera.getWorldDirection(dir).normalize();<br>  const left = new THREE.Vector3().crossVectors(dir, camera.up).normalize(); // 修正這裡<br>  moveCamera(left.multiplyScalar(moveStep));<br>});<br><br>document.getElementById(&#39;arrow-right&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  const dir = new THREE.Vector3();<br>  camera.getWorldDirection(dir).normalize();<br>  const right = new THREE.Vector3().crossVectors(camera.up, dir).normalize(); // 修正這裡<br>  moveCamera(right.multiplyScalar(moveStep));<br>});</pre><h4>前進（↑）</h4><pre>camera.getWorldDirection(dir).normalize();<br>moveCamera(dir.multiplyScalar(moveStep));</pre><ul><li>getWorldDirection(dir) 取得相機當前朝向（單位向量）。</li><li>normalize() 確保長度為 1。</li><li>multiplyScalar(moveStep) 讓它變成「朝向前方走 moveStep 單位」的位移向量。</li><li>moveCamera() 把它加到 targetPosition。</li></ul><h4>後退（↓）</h4><pre>camera.getWorldDirection(dir).normalize().negate();</pre><ul><li>與前進相同，但 .negate() 反向，變成往後走。</li></ul><h4>左移（←）</h4><pre>const left = new THREE.Vector3().crossVectors(dir, camera.up).normalize();</pre><ul><li>先求相機的前進方向 dir。</li><li>crossVectors(dir, camera.up) → 計算「前進方向 × 相機上方向」得到左向量。</li><li>為什麼用這樣的叉積順序？因為向量叉積遵守右手定則，(前 × 上) 會指向左邊。</li><li>normalize() → 長度調整為 1。</li><li>multiplyScalar(moveStep) → 調整成位移距離。</li></ul><h4>右移（→）</h4><pre>const right = new THREE.Vector3().crossVectors(camera.up, dir).normalize();</pre><ul><li>這次順序反過來 (上 × 前)，得到右向量。</li><li>其他流程跟左移相同。</li></ul><pre>// Animate<br>const clock = new THREE.Clock(); // 用來計算經過的時間<br>function animate() {<br>  requestAnimationFrame(animate); // 讓瀏覽器在下一幀再呼叫 animate()，形成無限循環<br><br>  const t = clock.getElapsedTime(); //  從 clock 啟動後累積的秒數<br>  if (duckModel) {<br>    duckModel.position.y = 0.5 + Math.sin(t * 2) * 0.05; // 產生一個隨時間變動的 -1 到 1 的波形<br>  }<br><br>  // 只 lerp camera.position，不去動 controls.target，保留使用者滑鼠控制<br>  camera.position.lerp(targetPosition, 0.05);<br>  controls.update();<br><br>  renderer.render(scene, camera);<br>}<br><br>animate();</pre><p>camera.position.lerp(targetPosition, 0.05);</p><ul><li>lerp() → 線性插值（Linear Interpolation），讓 camera.position 逐漸接近 targetPosition。</li><li>0.05 → 插值速度（每幀往目標移動 5% 的距離），數字越大移動越快。</li><li>「按箭頭 → 相機慢慢滑過去」的關鍵。</li></ul><pre>window.addEventListener(&#39;resize&#39;, () =&gt; {<br>  camera.aspect = window.innerWidth / window.innerHeight;<br>  camera.updateProjectionMatrix();<br>  renderer.setSize(window.innerWidth, window.innerHeight);<br>});</pre><p>監聽瀏覽器視窗大小改變事件，確保 3D 畫面比例正確</p><ul><li>camera.aspect → 更新相機的長寬比。</li><li>camera.updateProjectionMatrix() → 重新計算投影矩陣，防止畫面變形。</li><li>renderer.setSize() → 調整 WebGL 畫布的實際像素大小，避免拉伸或模糊。</li></ul><p>此範例適合用在身在一個巨大環境裡，只需要輕鬆漫遊的情境。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b86460e3a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js (5/5)導入 3D 模型（glTF / GLB）]]></title>
            <link>https://jacychu.medium.com/three-js-5-5-%E5%B0%8E%E5%85%A5-3d-%E6%A8%A1%E5%9E%8B-gltf-glb-a65cee644c0b?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a65cee644c0b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 06:57:44 GMT</pubDate>
            <atom:updated>2025-08-04T06:57:44.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>使用情境與程式碼</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*io-IuNLUVy03GxBRniMwJw.png" /></figure><p>📝 回顧章節：<a href="https://jacychu.medium.com/three-js-1-5-%E5%9F%BA%E7%A4%8E%E5%85%A5%E9%96%80%E8%88%87%E5%A0%B4%E6%99%AF%E6%90%AD%E5%BB%BA-faacf21769c6">Three.js (1/5)基礎入門與場景搭建</a><br>📝 回顧章節：<a href="https://medium.com/@jacychu/three-js-2-5-%E5%8A%A0%E5%85%A5%E5%85%89%E5%BD%B1-3d-%E6%9B%B4%E7%AB%8B%E9%AB%94-ae07924ee71a">Three.js (2/5)加入光影 3D 更立體</a><br>📝 回顧章節：<a href="https://jacychu.medium.com/%E4%BA%92%E5%8B%95%E6%80%A7%E5%8D%87%E7%B4%9A-124bae29eeb3">Three.js (3/5)互動性升級</a><br>📝 回顧章節：<a href="https://jacychu.medium.com/three-js-4-5-%E6%9D%90%E8%B3%AA%E8%88%87%E8%B2%BC%E5%9C%96-78fa17caa3ed">Three.js (4/5)材質與貼圖</a></p><h4>本章目標：</h4><ol><li>glTF 介紹</li><li>glTF vs. GLB 差別比較</li><li>使用方式</li><li>.gltf 範例</li><li>.glb 範例</li><li>小結</li></ol><p>glTF（GL Transmission Format） 是一種 3D 資產的交換格式，由 Khronos Group 提出，目的是讓 3D 模型能夠在 Web 或應用程式中快速載入和呈現。它就像 3D 世界的「JPEG 格式」，專門用來壓縮、傳輸和讀取模型。而 glTF 有兩種存儲形式：一種是 .gltf，一種是 .glb，它們本質上是同一種格式的不同包裝。</p><p><strong>🎨 一般是誰創作</strong><strong>.glTF 或 </strong><strong>.glb ？</strong>3D 設計師</p><p>使用工具如：</p><ul><li><strong>Blender</strong>（免費開源，支援輸出 .glb / .gltf）</li><li><strong>Maya / 3ds Max / Cinema 4D</strong></li><li><strong>Substance Painter</strong>（用來畫貼圖）</li><li>會把設計好的 3D 模型 → 匯出成 .glb 或 .gltf 格式，交給開發者用。</li></ul><h4>📂 glTF vs. GLB 差別比較</h4><h4>.gltf</h4><p>.gltf 是純文字（JSON 格式）檔案，它本身只包含模型的結構資訊，例如幾何形狀、材質設定、貼圖路徑等等。不過它不包含真正的「模型資料」和「貼圖」，這些東西會另外儲存在外部的 .bin 檔（幾何資料）和圖片檔（如 .jpg 或 .png）中。優點是容易閱讀和修改，很適合開發階段使用。缺點是載入時需要多次 HTTP 請求，因為一個模型可能會對應到多個檔案。</p><h4>.glb</h4><p>.glb 是 glTF 的二進位封裝形式。它把 .gltf 的所有資料（包括結構、幾何、貼圖圖片等）全部打包成一個二進位檔案，就像一個壓縮好的行李箱。此格式適合部署到線上，因為瀏覽器只要下載一次 .glb 檔，就能立即載入模型，不需要多次請求。雖然檔案體積可能稍大，但加載效率更好。缺點是它是二進位格式，不容易查看內容或進行手動修改，適合用於產品上線或模型分享。</p><p><strong>🧩 兩者的選擇</strong></p><ul><li>開發階段、需要手動編輯貼圖、材質設定，可以選擇 .gltf，容易查看與調整</li><li>已完成模型要展示或上線使用，推薦用 .glb，打包方便、讀取快速。</li></ul><h4>🎮 常見使用方式（Three.js）</h4><p>你會用 GLTFLoader 來載入模型：</p><pre>import { GLTFLoader } from &#39;three/examples/jsm/loaders/GLTFLoader.js&#39;;<br><br>const loader = new GLTFLoader();<br>loader.load(&#39;model.glb&#39;, (gltf) =&gt; {<br>  scene.add(gltf.scene); // 加入場景<br>});</pre><h4>📁 範例：.gltf vs .glb 檔案結構比較</h4><h4>.gltf</h4><pre>/model/<br>  ├── model.gltf         ← JSON 格式模型主檔 結構、材質、節點資料<br>  ├── model.bin          ← 二進位幾何資料 頂點/法線/UV 等幾何資料<br>  ├── texture_diffuse.jpg<br>  └── texture_normal.jpg</pre><h4>.glb</h4><pre>/model/<br>  └── model.glb ← 全部打包在一個檔案裡</pre><h4>引入 GLTFLoader</h4><pre>import { GLTFLoader } from &#39;three/examples/jsm/loaders/GLTFLoader.js&#39;;</pre><h4>建立 GLTFLoader 實例</h4><pre>const loader = new GLTFLoader();</pre><h4>載入模型</h4><pre>loader.load(&#39;/models/your_model.glb&#39;, (gltf) =&gt; {<br>  scene.add(gltf.scene); // 將模型加入場景<br>}, <br>(xhr) =&gt; {<br>  console.log((xhr.loaded / xhr.total * 100) + &#39;% loaded&#39;); // 載入進度<br>},<br>(error) =&gt; {<br>  console.error(&#39;An error happened&#39;, error); // 載入錯誤處理<br>});</pre><h4>模型載入成功後可以操作：</h4><pre>gltf.scene // 根節點，通常會加入 scene 中<br>gltf.animations // 若有動畫，可傳入 AnimationMixer 播放</pre><h3>.gltf 範例</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*WyFiqTmdPSsrg6L6lziH_g.png" /></figure><p>這是檔案結構</p><p>⚠️ 提醒：請使用 Live Server 或本地開發伺服器執行此專案，直接開啟 HTML 檔案會因為 ESM 模組限制而無法正常載入。</p><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;title&gt;Three.js GLTF Viewer&lt;/title&gt;<br>  &lt;style&gt;<br>    body { margin: 0; overflow: hidden; }<br>    canvas { display: block; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;script type=&quot;module&quot; src=&quot;main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>main.js</p><pre>import * as THREE from &#39;https://esm.sh/three&#39;;<br>import { OrbitControls } from &#39;https://esm.sh/three/examples/jsm/controls/OrbitControls.js&#39;;<br>import { GLTFLoader } from &#39;https://esm.sh/three/examples/jsm/loaders/GLTFLoader.js&#39;;<br><br>const scene = new THREE.Scene();<br>scene.background = new THREE.Color(0xdddddd);<br><br>const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);<br>camera.position.set(2, 2, 2);<br>camera.lookAt(0, 0, 0);<br><br>const renderer = new THREE.WebGLRenderer({ antialias: true });<br>renderer.setSize(window.innerWidth, window.innerHeight);<br>document.body.appendChild(renderer.domElement);<br><br>// 光線強化<br>const light = new THREE.HemisphereLight(0xffffff, 0x444444, 2);<br>scene.add(light);<br><br>// 輔助線<br>const grid = new THREE.GridHelper(10, 10);<br>scene.add(grid);<br>const axes = new THREE.AxesHelper(5);<br>scene.add(axes);<br><br>const controls = new OrbitControls(camera, renderer.domElement);<br>controls.update();<br><br>const loader = new GLTFLoader();<br><br>loader.load(&#39;models/Duck.gltf&#39;, function (gltf) {<br>  const model = gltf.scene;<br>  model.position.set(0, 0, 0);<br>  scene.add(model);<br>});<br><br>function animate() {<br>  requestAnimationFrame(animate);<br>  renderer.render(scene, camera);<br>}<br>animate();</pre><p>另外 models資料夾中的 Duck.gltf , Duck0.bin, DuckCM.png 可從<br><a href="https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck/glTF">https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck/glTF</a>下載，並放置於對應的檔案位置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kgbbkl210qai1yYFGW-XOA.gif" /></figure><h3>.glb 範例</h3><p><a href="https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck/glTF-Binary">https://github.com/KhronosGroup/glTF-Sample-Models/tree/main/2.0/Duck/glTF-Binary</a> 於此下載Duck.glb檔案，加到models資料夾中</p><p>將原本 load .gltf 檔案改成 load .glb檔案</p><pre>// loader.load(&#39;models/Duck.gltf&#39;, function (gltf) {<br>//   const model = gltf.scene;<br>//   model.position.set(0, 0, 0);<br>//   scene.add(model);<br>// });<br><br><br>loader.load(&#39;./models/Duck.glb&#39;, (gltf) =&gt; {<br>  const model = gltf.scene;<br>  console.log(&#39;Model loaded:&#39;, model);<br><br>  model.traverse((child) =&gt; {<br>    if (child.isMesh) {<br>      console.log(&#39;Found mesh:&#39;, child);<br>    }<br>  });<br>  model.scale.set(1, 1, 1);<br><br>  model.position.set(0, 0, 0);<br>  scene.add(model);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ZHRsALURWUrT25tVaSqZUg.png" /></figure><h4>📚 結語：從 Part 1 到 Part 5，奠定 Three.js 開發基礎</h4><p>經過 Part 1 到 Part 5 的完整學習，我們已經從 Three.js 的最基本場景設定開始，逐步掌握了建構 3D 應用的核心概念。這五個階段涵蓋了：</p><ul><li><strong>Part 1</strong>：建立渲染器、場景與相機，搭起 3D 世界的骨架</li><li><strong>Part 2</strong>：添加光源與陰影，讓畫面更加立體與真實</li><li><strong>Part 3</strong>：整合 OrbitControls 與 dat.GUI，加入互動性與參數控制</li><li><strong>Part 4</strong>：使用各種材質與貼圖，呈現更豐富的視覺效果</li><li><strong>Part 5</strong>：載入 .glb / .gltf 模型，實現與設計資源的整合運用</li></ul><p>建立 Three.js 的初階實戰力，只是起點。未來可以進一步探索動畫、物理引擎、粒子特效、模型互動、Scroll-based 動畫，甚至與後端資料串接，開發真正可應用的 3D Web 應用。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65cee644c0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js (4/5)材質與貼圖]]></title>
            <link>https://jacychu.medium.com/three-js-4-5-%E6%9D%90%E8%B3%AA%E8%88%87%E8%B2%BC%E5%9C%96-78fa17caa3ed?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fa17caa3ed</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 08:35:03 GMT</pubDate>
            <atom:updated>2025-08-04T06:59:04.548Z</atom:updated>
            <content:encoded><![CDATA[<h4>從基礎材質到真實感貼圖</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h83tiTkk68aAx6SA6QIJLw.png" /></figure><p>📝 回顧章節：<a href="https://jacychu.medium.com/three-js-1-5-%E5%9F%BA%E7%A4%8E%E5%85%A5%E9%96%80%E8%88%87%E5%A0%B4%E6%99%AF%E6%90%AD%E5%BB%BA-faacf21769c6">Three.js (1/5)基礎入門與場景搭建</a><br>📝 回顧章節：<a href="https://medium.com/@jacychu/three-js-2-5-%E5%8A%A0%E5%85%A5%E5%85%89%E5%BD%B1-3d-%E6%9B%B4%E7%AB%8B%E9%AB%94-ae07924ee71a">Three.js (2/5)加入光影 3D 更立體</a><br>📝 回顧章節：<a href="https://jacychu.medium.com/%E4%BA%92%E5%8B%95%E6%80%A7%E5%8D%87%E7%B4%9A-124bae29eeb3">Three.js (3/5)互動性升級</a></p><h4>本章目標：</h4><ul><li>常用材質介紹</li><li>貼圖及TextureLoader 載入介紹</li><li>搭配 OrbitControls 觀察貼圖細節</li></ul><h3>1.常見材質介紹</h3><h4>(1) MeshBasicMaterial</h4><pre>new THREE.MeshBasicMaterial({ color: 0xff0000 })</pre><ul><li>不吃光，不管加幾個光源，它都一樣亮。</li><li>適合：UI、debug 用、背景不想受光源影響的模型。</li></ul><h4>(2) MeshPhongMaterial</h4><pre>new THREE.MeshPhongMaterial({<br>  color: 0x00ff00,<br>  shininess: 100<br>});</pre><ul><li>吃光，可產生「高光反射」，看起來光滑有亮點。</li><li>可調整高光強度 (shininess)，支援環境光、點光源、平行光。</li><li>適合：一般模型、有光澤的東西（塑膠、陶瓷等）。</li></ul><h4>(3) MeshStandardMaterial</h4><pre>new THREE.MeshStandardMaterial({<br>  color: 0x0000ff,<br>  metalness: 0.8,<br>  roughness: 0.2<br>});</pre><ul><li>真實感最強（物理光照材質 PBR），支援金屬度 (metalness)、粗糙度 (roughness)。</li><li>支援所有光源類型，效果最豐富。</li><li>適合：高質感場景、產品展示、遊戲角色。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*N3LiOU3AzJOXY27JTpsLLw.png" /></figure><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;材質比較&lt;/title&gt;<br>  &lt;style&gt; body { margin: 0; } canvas { display: block; } &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;script type=&quot;module&quot;&gt;<br>    import * as THREE from &#39;https://cdn.skypack.dev/three@0.152.2&#39;;<br>    const scene = new THREE.Scene();<br>    const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);<br>    camera.position.set(0, 2, 8);<br>    camera.lookAt(0, 0, 0);<br><br>    const renderer = new THREE.WebGLRenderer({ antialias: true });<br>    renderer.setSize(window.innerWidth, window.innerHeight);<br>    document.body.appendChild(renderer.domElement);<br><br>    const light = new THREE.DirectionalLight(0xffffff, 1);<br>    light.position.set(5, 5, 5);<br>    scene.add(light);<br><br>    const grid = new THREE.GridHelper(10, 10);<br>    scene.add(grid);<br><br>    // 建三種球體<br>    const geometry = new THREE.SphereGeometry(1, 32, 32);<br><br>    // Basic 不受光影影響（永遠亮）<br>    const basic = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0xff0000 }));<br>    basic.position.x = -3;<br>    scene.add(basic);<br><br>    // Phong 支援高光<br>    const phong = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({ color: 0x00ff00, shininess: 100 }));<br>    phong.position.x = 0;<br>    scene.add(phong);<br>    // Standard 支援金屬感、粗糙度（PBR）<br>    const standard = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({<br>      color: 0x0000ff,<br>      metalness: 1,<br>      roughness: 0.2<br>    }));<br>    standard.position.x = 3;<br>    scene.add(standard);<br>    renderer.render(scene, camera);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUtPt6QNAYE3XYapkK2NjQ.png" /></figure><h3>2. 貼圖及TextureLoader 載入介紹</h3><h4>(1) 貼圖介紹</h4><h4>map 顏色貼圖 / 色彩圖</h4><p>最基本的貼圖，決定物體表面的主要顏色。看到的「材質外觀」通常是這張圖決定的。<br>📌 對應材質的 color 屬性（會被取代）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BM5KZegZuoa2pi6Lzn8crw.png" /></figure><h4>normalMap 法線貼圖</h4><p>利用 RGB 值模擬表面凹凸感，不需增加多邊形數量。<br>📌 高效能、現代主流方式，常見於遊戲與動畫角色的皮膚或石頭表面。<br>❗ 需要有對應的 UV 展開，並且燈光效果才能展現其立體感。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*357f4TFO3Xbb6TBkUl9DQg.png" /></figure><h4>roughnessMap 粗糙度貼圖</h4><p>控制每個像素的粗糙程度（值從 0～1）：<br>白色 = 非常粗糙（反光模糊），黑色 = 非常光滑（像鏡子）<br>📌 適用於 MeshStandardMaterial / MeshPhysicalMaterial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxTFf5vD9W_A1HeHTQ6mNA.png" /><figcaption>有點不明顯</figcaption></figure><h4>metalnessMap 金屬度貼圖</h4><p>控制每個像素的金屬感（0 = 絕對非金屬，1 = 完全金屬）<br>白色像金屬，黑色像塑膠或木頭。<br>📌 搭配 roughnessMap 可產生極真實的材質外觀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KahDxtJ9k5duhlgpFkd1YA.png" /></figure><h4>(2) TextureLoader介紹</h4><p>Three.js 提供的圖片載入工具，用來從圖片檔案載入貼圖（texture）。可載入 JPG、PNG 等常見圖片格式，並回傳 THREE.Texture 物件，供材質使用。</p><h4>📦 建立 TextureLoader 實例</h4><pre>const loader = new THREE.TextureLoader();<br>const colorTexture = loader.load(&quot;./textures/metal/SheetMetal001_1K-JPG_Color.jpg&quot;);</pre><ul><li>只需要建立一個 loader 實例，就可以載入多張貼圖。</li><li>此 loader 實例具備 .load() 方法，可以載入圖片並轉為貼圖。</li><li>.load()最常見的用法就是只傳入路徑，立即取得貼圖。</li><li>載入是非同步的，但 Three.js 會自動處理圖片還沒載完的情況。</li></ul><p>材質參考網站：<a href="https://ambientcg.com/view?id=SheetMetal001&amp;utm_source=chatgpt.com">https://ambientcg.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4sEMOINfKhXPrWvKgKiyg.png" /></figure><h3>4. 搭配 OrbitControls 觀察貼圖細節</h3><p>詳細OrbitControls介紹可以參考上個章節</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV8WiujjOGbaxQ3CjLyVuQ.png" /></figure><p>預先準備好材質圖檔，放到對應檔案夾中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*7A__5nsxkka26TclOCwmQg.png" /></figure><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;Three.js Texture Mode Selector&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      margin: 0;<br>      overflow: hidden;<br>    }<br><br>    canvas {<br>      display: block;<br>    }<br><br>    .buttons {<br>      position: absolute;<br>      top: 10px;<br>      left: 10px;<br>      z-index: 10;<br>    }<br><br>    button {<br>      margin: 2px;<br>      padding: 5px 10px;<br>      background-color: #eee;<br>      border: 1px solid #ccc;<br>      cursor: pointer;<br>    }<br><br>    button.active {<br>      background-color: #007bff;<br>      color: white;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div class=&quot;buttons&quot;&gt;<br>    &lt;button data-mode=&quot;color&quot;&gt;Color&lt;/button&gt;<br>    &lt;button data-mode=&quot;normal&quot;&gt;Normal&lt;/button&gt;<br>    &lt;button data-mode=&quot;roughness&quot;&gt;Roughness&lt;/button&gt;<br>    &lt;button data-mode=&quot;metalness&quot;&gt;Metalness&lt;/button&gt;<br>    &lt;button data-mode=&quot;combined&quot;&gt;Combined&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;canvas id=&quot;webgl&quot;&gt;&lt;/canvas&gt;<br><br>  &lt;script type=&quot;module&quot;&gt;<br>    import * as THREE from &quot;https://esm.sh/three&quot;;<br>    import { OrbitControls } from &quot;https://esm.sh/three/examples/jsm/controls/OrbitControls.js&quot;;<br><br>    const scene = new THREE.Scene();<br>    const camera = new THREE.PerspectiveCamera(<br>      75,<br>      window.innerWidth / window.innerHeight,<br>      0.1,<br>      1000<br>    );<br>    camera.position.set(2, 2, 3);<br><br>    const renderer = new THREE.WebGLRenderer({<br>      canvas: document.querySelector(&quot;#webgl&quot;),<br>    });<br>    renderer.setSize(window.innerWidth, window.innerHeight);<br>    renderer.setPixelRatio(window.devicePixelRatio);<br><br>    // 加上loader<br>    const loader = new THREE.TextureLoader();<br>    const colorTexture = loader.load(&quot;./textures/metal/SheetMetal001_1K-JPG_Color.jpg&quot;);<br>    const normalTexture = loader.load(&quot;./textures/metal/SheetMetal001_1K-JPG_NormalGL.jpg&quot;);<br>    const roughnessTexture = loader.load(&quot;./textures/metal/SheetMetal001_1K-JPG_Roughness.jpg&quot;);<br>    const metalnessTexture = loader.load(&quot;./textures/metal/SheetMetal001_1K-JPG_Metalness.jpg&quot;);<br><br>    const geometry = new THREE.BoxGeometry(1, 1, 1);<br>    const material = new THREE.MeshStandardMaterial({ color: 0x999999 });<br>    const cube = new THREE.Mesh(geometry, material);<br>    scene.add(cube);<br><br>    const light = new THREE.DirectionalLight(0xffffff, 8);<br>    light.position.set(5, 5, 5);<br>    scene.add(light);<br><br>    const ambient = new THREE.AmbientLight(0xffffff, 0.3);<br>    scene.add(ambient);<br><br>    const controls = new OrbitControls(camera, renderer.domElement);<br>    controls.enableDamping = true;<br><br>    window.addEventListener(&quot;resize&quot;, () =&gt; {<br>      camera.aspect = window.innerWidth / window.innerHeight;<br>      camera.updateProjectionMatrix();<br>      renderer.setSize(window.innerWidth, window.innerHeight);<br>    });<br><br>    // 設定貼圖<br>    function setMode(mode) {<br>      material.map = null;<br>      material.normalMap = null;<br>      material.roughnessMap = null;<br>      material.metalnessMap = null;<br><br>      if (mode === &quot;color&quot;) {<br>        material.map = colorTexture;<br>      } else if (mode === &quot;normal&quot;) {<br>        material.normalMap = normalTexture;<br>      } else if (mode === &quot;roughness&quot;) {<br>        material.roughnessMap = roughnessTexture;<br>      } else if (mode === &quot;metalness&quot;) {<br>        material.metalnessMap = metalnessTexture;<br>      } else if (mode === &quot;combined&quot;) {<br>        material.map = colorTexture;<br>        material.normalMap = normalTexture;<br>        material.roughnessMap = roughnessTexture;<br>        material.metalnessMap = metalnessTexture;<br>      }<br><br>      material.metalness = 1.0;<br>      material.roughness = 1;<br>      material.needsUpdate = true;<br><br>      document.querySelectorAll(&quot;.buttons button&quot;).forEach((btn) =&gt; {<br>        btn.classList.toggle(&quot;active&quot;, btn.dataset.mode === mode);<br>      });<br>    }<br><br>    document.querySelectorAll(&quot;.buttons button&quot;).forEach((btn) =&gt; {<br>      btn.addEventListener(&quot;click&quot;, () =&gt; {<br>        setMode(btn.dataset.mode);<br>      });<br>    });<br><br>    // Default<br>    setMode(&quot;combined&quot;);<br><br>    function animate() {<br>      requestAnimationFrame(animate);<br>      cube.rotation.y += 0.01;<br>      controls.update();<br>      renderer.render(scene, camera);<br>    }<br>    animate();<br>  &lt;/script&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>⚠️ 提醒：請使用 Live Server 或本地開發伺服器執行此專案，直接開啟 HTML 檔案會因為 ESM 模組限制而無法正常載入。</p><p>操作展示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKBua16x3GtCF0J5953Ayg.gif" /></figure><p>在本篇中，依序介紹了 Three.js 常用的材質種類（Basic、Phong、Standard），並實際比較了它們在光照下的差異。接著，透過 TextureLoader 載入各種貼圖（顏色、法線、粗糙度、金屬度），讓物件表面更具真實感。最後搭配 OrbitControls，可以自由旋轉觀察材質細節。</p><h3>📘 延伸學習方向</h3><p>掌握基本材質與貼圖的使用後，可以繼續探索更進階的材質應用與細節控制，例如：</p><p>✅ AO Map（環境光遮罩）：模擬陰影遮蔽效果，讓物體縫隙更有深度感。<br>✅ Displacement Map（置換貼圖）：直接影響模型幾何形狀，讓表面產生真實凹凸，而非只是視覺效果。<br>✅ HDRI 環境光照與反射貼圖：利用高動態範圍影像模擬自然場景光照與真實反射。<br>✅ 自訂 Shader 材質（如 ShaderMaterial / NodeMaterial）：完全掌控視覺風格，實現動畫貼圖、漸層變化、互動效果等。</p><p>🚪 前往下一章節：<a href="https://jacychu.medium.com/three-js-5-5-%E5%B0%8E%E5%85%A5-3d-%E6%A8%A1%E5%9E%8B-gltf-glb-a65cee644c0b">Three.js (5/5)導入 3D 模型 glTF / GLB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fa17caa3ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three.js (3/5)互動性升級]]></title>
            <link>https://jacychu.medium.com/%E4%BA%92%E5%8B%95%E6%80%A7%E5%8D%87%E7%B4%9A-124bae29eeb3?source=rss-1f5721ebe68b------2</link>
            <guid isPermaLink="false">https://medium.com/p/124bae29eeb3</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Jacy Chu]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 08:54:41 GMT</pubDate>
            <atom:updated>2025-08-01T08:37:37.099Z</atom:updated>
            <content:encoded><![CDATA[<h4>用 OrbitControls 與 lil-gui 提升 Three.js 立方體互動性</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnsrsMX3amiqa3ivwDn2nw.png" /></figure><p>📝 回顧章節：<a href="https://jacychu.medium.com/three-js-1-5-%E5%9F%BA%E7%A4%8E%E5%85%A5%E9%96%80%E8%88%87%E5%A0%B4%E6%99%AF%E6%90%AD%E5%BB%BA-faacf21769c6">Three.js (1/5)基礎入門與場景搭建</a><br>📝 回顧章節：<a href="https://medium.com/@jacychu/three-js-2-5-%E5%8A%A0%E5%85%A5%E5%85%89%E5%BD%B1-3d-%E6%9B%B4%E7%AB%8B%E9%AB%94-ae07924ee71a">Three.js (2/5)加入光影 3D 更立體</a></p><h4>本章目標：</h4><ul><li>顯示一個旋轉的立方體（Cube）</li><li>加入 OrbitControls 支援滑鼠旋轉、縮放、平移</li><li>加入 lil-gui 控制面板，自由調整 Cube 的參數（如位置、顏色、是否自轉等）</li></ul><h3>🌀 OrbitControls：滑鼠控制 3D 相機</h3><ul><li>用途：環繞目標旋轉（繞一個點轉動）、縮放、平移</li><li>常見用途：產品展示、模型檢視器</li></ul><h4>引用方式</h4><pre>import { OrbitControls } from &quot;https://esm.sh/three/examples/jsm/controls/OrbitControls.js&quot;;</pre><h4>使用方式</h4><pre>const controls = new OrbitControls(camera, renderer.domElement);</pre><p>讓滑鼠控制綁定在渲染器的 &lt;canvas&gt; 上，並控制這個 camera。<br>可以加上其他選項（可選）：</p><pre>controls.enableDamping = true;   // 維持物理慣性<br>controls.dampingFactor = 0.05;   // 控制 Damping 速度<br>controls.autoRotate = true;      // 自動旋轉（可當背景動畫）</pre><h4>加入 animate loop</h4><pre>function animate() {<br>  requestAnimationFrame(animate); // 每一幀呼叫一次<br>  controls.update();              // 重要：更新控制器狀態<br>  renderer.render(scene, camera); // 渲染場景<br>}<br><br>animate(); // 啟動動畫迴圈</pre><p>操控滑鼠：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zdNJX7ALEitsE5S35J82Pg.gif" /></figure><p>main.js：</p><pre>import * as THREE from &quot;https://esm.sh/three&quot;;<br>import { OrbitControls } from &quot;https://esm.sh/three/examples/jsm/controls/OrbitControls.js&quot;;<br><br>const scene = new THREE.Scene();<br><br>const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);<br>camera.position.z = 3;<br><br>const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector(&quot;#webgl&quot;) });<br>renderer.setSize(window.innerWidth, window.innerHeight);<br>renderer.setPixelRatio(window.devicePixelRatio);<br><br>const geometry = new THREE.BoxGeometry();<br>const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });<br>const cube = new THREE.Mesh(geometry, material);<br>scene.add(cube);<br><br>const light = new THREE.DirectionalLight(0xffffff, 1);<br>light.position.set(2, 2, 5);<br>scene.add(light);<br><br>const controls = new OrbitControls(camera, renderer.domElement);<br><br>function animate() {<br>  requestAnimationFrame(animate);<br>  controls.update(); <br>  renderer.render(scene, camera);<br>}<br><br>animate();</pre><p>💡<strong>延伸：其他幾種常見的控制器（Controls）</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*platEXv7ZwvTVyZ1IUZ17Q.png" /></figure><p>主要用法都差不多，設定略為不同。</p><h3>🎛️ lil-gui JS GUI控制面板</h3><ul><li>lil-gui 是 dat.GUI 的改良版本。</li><li>支援現代瀏覽器與模組化開發。</li><li>相容性佳、效能更好、樣式更簡潔。</li><li>官網： <a href="https://lil-gui.georgealways.com/">https://lil-gui.georgealways.com/</a></li></ul><h4>和 dat.GUI 的差異</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*je4JtAIUsGbpnZmmskhVGA.png" /></figure><h4>引入方式（ESM）</h4><pre>import GUI from &quot;https://esm.sh/lil-gui&quot;;</pre><h4>建立 GUI</h4><pre>const gui = new GUI();</pre><h4>控制顏色（addColor）</h4><pre>gui.addColor(params, &quot;color&quot;).onChange((value) =&gt; {<br>  material.color.set(value);<br>});</pre><ul><li>會產生一個「顏色選擇器」</li><li>每次改變都會觸發 onChange 事件，修改材質顏色</li></ul><h4>控制數值（add）</h4><pre>gui.add(params, &quot;rotationSpeed&quot;, 0, 0.1, 0.001);<br>// gui.add(object, property, min, max, step);</pre><ul><li>控制 cube 的旋轉速度</li><li>可設定數值範圍與步進值</li></ul><p>min：數值的最小值（滑桿起點）<br>max：數值的最大值（滑桿終點）<br>step：每次滑動的變動步長（數值精度）</p><p>操作展示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDo-L-9xCmssIQXZUuOv1A.gif" /></figure><p>main.js：</p><pre>import * as THREE from &quot;https://esm.sh/three&quot;;<br>import GUI from &quot;https://esm.sh/lil-gui&quot;;<br><br>const scene = new THREE.Scene();<br><br>const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);<br>camera.position.z = 3;<br><br>const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector(&quot;#webgl&quot;) });<br>renderer.setSize(window.innerWidth, window.innerHeight);<br>renderer.setPixelRatio(window.devicePixelRatio);<br><br>const geometry = new THREE.BoxGeometry();<br>const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });<br>const cube = new THREE.Mesh(geometry, material);<br>scene.add(cube);<br><br>const light = new THREE.DirectionalLight(0xffffff, 1);<br>light.position.set(2, 2, 5);<br>scene.add(light);<br><br>const gui = new GUI();<br>const params = {<br>  color: 0x00ff00,<br>  rotationSpeed: 0.01<br>};<br>gui.addColor(params, &quot;color&quot;).onChange((value) =&gt; {<br>  material.color.set(value);<br>});<br>gui.add(params, &quot;rotationSpeed&quot;, 0, 0.1, 0.001);<br><br>window.addEventListener(&quot;resize&quot;, () =&gt; {<br>  camera.aspect = window.innerWidth / window.innerHeight;<br>  camera.updateProjectionMatrix();<br>  renderer.setSize(window.innerWidth, window.innerHeight);<br>});<br><br>function animate() {<br>  requestAnimationFrame(animate);<br>  cube.rotation.y += params.rotationSpeed;<br>  renderer.render(scene, camera);<br>}<br>animate();</pre><p>💡<strong>延伸：</strong><strong>lil-gui 實用方法總覽</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*unqbl-EuiE5ZgDDygkltBA.png" /></figure><h3>🧪練習範例整合</h3><p>結合上述說明，合併成簡單但完整的範例！</p><p>⚠️ 提醒：請使用 Live Server 或本地開發伺服器執行此專案，直接開啟 HTML 檔案會因為 ESM 模組限制而無法正常載入。</p><p>index.html 檔案內容</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;title&gt;Three.js Vanilla&lt;/title&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;./styles.css&quot; /&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;canvas id=&quot;webgl&quot;&gt;&lt;/canvas&gt;<br>  &lt;script type=&quot;module&quot; src=&quot;./main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>main.js 檔案內容</p><pre>import * as THREE from &quot;https://esm.sh/three&quot;;<br>import { OrbitControls } from &quot;https://esm.sh/three/examples/jsm/controls/OrbitControls.js&quot;;<br>import GUI from &quot;https://esm.sh/lil-gui&quot;;<br><br>const scene = new THREE.Scene();<br><br>const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);<br>camera.position.z = 3;<br><br>const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector(&quot;#webgl&quot;) });<br>renderer.setSize(window.innerWidth, window.innerHeight);<br>renderer.setPixelRatio(window.devicePixelRatio);<br><br>const geometry = new THREE.BoxGeometry();<br>const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });<br>const cube = new THREE.Mesh(geometry, material);<br>scene.add(cube);<br><br>const light = new THREE.DirectionalLight(0xffffff, 1);<br>light.position.set(2, 2, 5);<br>scene.add(light);<br><br>const controls = new OrbitControls(camera, renderer.domElement);<br><br>const gui = new GUI();<br>const params = {<br>  color: 0x00ff00,<br>  rotationSpeed: 0.01,<br>  autoRotate: true<br>};<br>gui.addColor(params, &quot;color&quot;).onChange((value) =&gt; {<br>  material.color.set(value);<br>});<br>gui.add(params, &quot;rotationSpeed&quot;, 0, 0.1, 0.001);<br>gui.add(params, &quot;autoRotate&quot;).name(&quot;啟用自轉&quot;);<br><br>window.addEventListener(&quot;resize&quot;, () =&gt; {<br>  camera.aspect = window.innerWidth / window.innerHeight;<br>  camera.updateProjectionMatrix();<br>  renderer.setSize(window.innerWidth, window.innerHeight);<br>});<br><br>function animate() {<br>  requestAnimationFrame(animate);<br>  if (params.autoRotate) {<br>    cube.rotation.y += params.rotationSpeed;<br>  }<br>  renderer.render(scene, camera);<br>}<br>animate();</pre><p>style.css</p><pre>body {<br>  margin: 0;<br>  overflow: hidden;<br>  background-color: black;<br>}<br>canvas {<br>  display: block;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2-N3OtfQcwEuVA7XfkDWQ.gif" /></figure><p>透過這個範例，展示用 OrbitControls 操控視角，並透過 lil-gui 即時調整 Cube 的參數，是進入 Three.js 互動應用的好起點。</p><p>🚪 前往下一章節：<a href="https://jacychu.medium.com/three-js-4-5-%E6%9D%90%E8%B3%AA%E8%88%87%E8%B2%BC%E5%9C%96-78fa17caa3ed">Three.js (4/5)材質與貼圖</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124bae29eeb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>