title
stringlengths
2
136
text
stringlengths
20
75.4k
在網頁應用程式中使用本地檔案 - Web APIs
在網頁應用程式中使用本地檔案 ============== 現在可以透過新增至 HTML5 DOM 的 File API 讓 web 內容要求使用者選取本地端的檔案後讀取被選取檔案中的內容。檔案的選取動作可以使用 HTML 的 `input` 元素,或是用拖曳檔案(drag and drop)的方式來完成。 如果你想要使用 DOM 檔案 API 的文件擴展或是其他 Chrome 程式碼,你可以參考使用 DOM 檔案 API 在 FireFox 外觀代碼中。 使用 HTML 選擇本地檔案 -------------- HTML 語法: ```html <input type="file" id="input" /> ``` File API 可以從 `File` 物件中讀取 `FileList` ,`FileList` 內包含使用者所選取的檔案。 如果使用者只選擇一個檔案,那麼我們只需要考慮第一個檔案物件。 使用 DOM 獲取選擇的檔案: ```js var selectedFile = document.getElementById("input").files[0]; ``` 使用 jQuery 獲取選擇的檔案: ```js var selectedFile = $("#input").get(0).files[0]; var selectedFile = $("#input")[0].files[0]; ``` **備註:** 如果獲取 "files is undefined" 錯誤: 代表未選擇正確的 HTML 元素, 這時忘記 jQuery 回傳符合 DOM 元素的清單. 改使用 DOM 元素呼叫 "files" 方法. 使用 change event 獲取選擇的檔案 ----------------------- 使用 File API 選擇單一檔案是非常簡單的,如下 ```html <input type="file" id="input" onchange="handleFiles(this.files)" /> ``` 當使用者選取一個檔案,呼叫 `handleFiles()` 會得到一個 `FileList` 的物件。`FileList` 裡面還會有一個 `File` 的物件,裡面的東西就是使用者選取的檔案。 如果你想要讓使用者一次選擇多個檔案,可以在 `input` 元素中使用 `multiple` 的屬性: ```html <input type="file" id="input" multiple="true" onchange="handleFiles(this.files)" /> ``` 在上述這個例子中,檔案名單會傳遞到 `handleFiles()` 函數,其中包含了使用者選的每個檔案 `File` 物件。 ### 使用 EventListener 動態地監聽 如果使用了其他的函數庫(jQuery),你會需要使用 `EventTarget.addEventListener()` 去監聽事件,例如: ```js var inputElement = document.getElementById("inputField"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { var fileList = this.files; /\* now you can work with the file list \*/ } ``` 在這個例子中,`handleFiles()` 函數找尋檔案清單而非接收參數, 因為這樣增加的 event listeners 不能接受參數. 獲得選取檔案的資訊 --------- 由 DOM 提供的 `FileList` 物件代表使用者選取的所有檔案,每個又是 `File` 物件。可以藉由 `FileList` 的 length 屬性得知使用者選取的檔案數量: ```js var numFiles = files.length; ``` 使用陣列獲取 `File` 物件: ```js for (var i = 0; i < files.length; i++) { var file = files[i]; .. } ``` 上述的例子顯示獲取在檔案清單裡所有檔案物件的方法。 `File` 提供三個包含檔案重要訊息的屬性。 `name` 唯讀的檔案名稱,並未包含檔案路徑。 `size` 為 64 位元的整數,用以表示檔案的 byte 的長度。 `type` 為唯讀字串。表示檔案的 MIME-type 。若是無法取得檔案的 Mime-type ,則其值會是一個空字串 `""`。 使用 click() 方法隱藏檔案輸入元素 --------------------- 從 Gecko 2.0 開始,為了顯示個人化開啟檔案的 UI 和使用者選擇的檔案可以隱藏 `<input>` (en-US) 元素和顯示個人化的設計。可以藉由設置 CSS 「display:none」 和對 `<input>` (en-US) 元素呼叫 `click()` 方法。 HTML 如下: ```html <input type="file" id="fileElem" multiple="true" accept="image/\*" style="display:none" onchange="handleFiles(this.files)" /> <a href="#" id="fileSelect">Select some files</a> ``` `doClick()` 方法: ```js var fileSelect = document.getElementById("fileSelect"), fileElem = document.getElementById("fileElem"); fileSelect.addEventListener( "click", function (e) { if (fileElem) { fileElem.click(); } e.preventDefault(); // prevent navigation to "#" }, false, ); ``` 很明顯的,可以使用 CSS 來設計新的上傳檔案的按鈕。 使用拖放選取檔案 -------- 使用者可以使用拖放來選取檔案,首先要設置放的區域,確定文件可以接收放的檔案,方法如下: ```js var dropbox; dropbox = document.getElementById("dropbox"); dropbox.addEventListener("dragenter", dragenter, false); dropbox.addEventListener("dragover", dragover, false); dropbox.addEventListener("drop", drop, false); ``` 在這個範例中,我們將 ID "dropbox" 設為放的區域,這是由於我們監聽了 `dragenter`、`dragover` 和 `drop`事件。 我們甚至不需要處理 `dragenter` 和 `dragover` 事件,所以這些函數很簡單。他們阻止了事件的傳播和預設事件的發生: ```js function dragenter(e) { e.stopPropagation(); e.preventDefault(); } function dragover(e) { e.stopPropagation(); e.preventDefault(); } ``` 神奇的 `drop()` 函數: ```js function drop(e) { e.stopPropagation(); e.preventDefault(); var dt = e.dataTransfer; var files = dt.files; handleFiles(files); } ``` `這邊我們用 dataTransfer` 來獲取檔案清單, 並傳遞給 `handleFiles()`。 我們可以發現,不論使用拖放或是其他取得檔案,處理檔案的方式都是相同。 範例:顯示選取的圖片 ---------- 假設要開發一個分享照片的網站,想使用 HTML5 來讓使用者在上傳圖片前預覽縮圖。簡單來說就是像先前討論地一樣建立 input 元素或是 drop 區域,接著再呼叫類似 `handleFiles()` 的函數。 ```js function handleFiles(files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /image.\*/; if (!file.type.match(imageType)) { continue; } var img = document.createElement("img"); img.classList.add("obj"); img.file = file; preview.appendChild(img); var reader = new FileReader(); reader.onload = (function (aImg) { return function (e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); } } ``` 這邊迴圈處理了使用者選取的每個檔案並檢查每個檔案的類型是不是圖檔(藉由使用正規表達式檢查是否符合字串 "image.\*")。每一個是圖片的檔案,我們創建一個 `img` 元素。CSS 被使用來美化外框、陰影、還有設定圖片的尺寸,所以那些並不需要在這邊寫入。 為了使圖片可以在 DOM 裡面更容易被找到,所以每個圖片都有設定 CSS class 「obj」。 我們也在每個圖檔標記 `file` 屬性以辨認 `File`;這使我們更容易取得真正要上傳的圖檔。最後我們使用`Node.appendChild()` (en-US) 在文件中增加縮圖的元素。 `FileReader` 處理要非同步讀取的圖檔並跟 `img` 元素連接。在創建 `FileReader` 物件後,我們設置了 `onload`並 呼叫 `readAsDataURL()` 在背景呼叫讀取的程序。當所有圖檔都被讀取時,他們被轉換為傳到 `onload callback` 的 `data` URL。 這個範例簡易的設置`img` 元素的 `src` 屬性來讀取圖檔並在螢幕上顯示。 使用 object URLs -------------- Gecko 2.0 支援 DOM 的`window.URL.createObjectURL()` (en-US) 和 `window.URL.revokeObjectURL()` (en-US) 方法。可以藉由這些方法創建表示任何為 DOM `File` 物件的 data URL 字串,包含了使用者電腦上的檔案。 可以使 `File` 物件作為 HTML 元素 URL 的參考,創建 object URL 的方法: ```js var objectURL = window.URL.createObjectURL(fileObj); ``` object URL 為表示 `File` 物件的字串。即使已經對相同檔案創建了 object URL,每次呼叫 `window.URL.createObjectURL()` (en-US),就會創建一個 object URL。當文檔卸載時他們將會被自動釋放,如果要動態地使用,需要呼叫 `window.URL.revokeObjectURL()` (en-US) 釋放: ```js window.URL.revokeObjectURL(objectURL); ``` 範例:使用 object URLs 顯示圖片 ---------------------- 這個範例使用 object URLs 顯示圖像縮圖。此外也顯示了其他包含檔案名稱和檔案大小的訊息。線上範例 (註:瀏覽器版本要求 11/22 之後的火狐版本)。 **備註:** 這個 API 在較早的 Firefox 4 betas 存在但是 11/22 號後的版本有改變, 所以確定瀏覽器在最新的版本! HTML: ```html <input type="file" id="fileElem" multiple accept="image/\*" style="display:none" onchange="handleFiles(this.files)" /> <a href="#" id="fileSelect">Select some files</a> <div id="fileList"> <p>No files selected!</p> </div> ``` This establishes our file `<input>` (en-US) element, as well as a link that invokes the file picker, since we keep the file input hidden to prevent that less-than-attractive UI from being displayed. This is explained above in the section Using hidden file input elements using the click() method, as is the `doClick()` method that invokes the file picker. The `handleFiles()` method follows: ```js var fileSelect = document.getElementById("fileSelect"), fileElem = document.getElementById("fileElem"), fileList = document.getElementById("fileList"); fileSelect.addEventListener( "click", function (e) { if (fileElem) { fileElem.click(); } e.preventDefault(); // prevent navigation to "#" }, false, ); function handleFiles(files) { if (!files.length) { fileList.innerHTML = "<p>No files selected!</p>"; } else { var list = document.createElement("ul"); for (var i = 0; i < files.length; i++) { var li = document.createElement("li"); list.appendChild(li); var img = document.createElement("img"); img.src = window.URL.createObjectURL(files[i]); img.height = 60; img.onload = function () { window.URL.revokeObjectURL(this.src); }; li.appendChild(img); var info = document.createElement("span"); info.innerHTML = files[i].name + ": " + files[i].size + " bytes"; li.appendChild(info); } fileList.appendChild(list); } } ``` This starts by fetching the URL of the `<div>` with the ID "fileList". This is the block into which we'll insert out file list, including thumbmails. If the `FileList` object passed to `handleFiles()` is `null`, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows: 1. A new unordered list (`<ul>` (en-US) element is created. 2. The new list element is inserted into the `<div>` block by calling its `element.appendChild()` method. 3. For each `File` in the `FileList` represented by `files`: 1. Create a new list item (`<li>` (en-US)) element and insert it into the list. 2. Create a new image (`<img>` (en-US)) element. 3. Set the image's source to a new object URL representing the file, using `window.URL.createObjectURL()` (en-US) to create the blob URL. 4. Set the image's height to 60 pixels. 5. Set up the image's load event handler to release the object URL, since it's no longer needed once the image has been loaded. This is done by calling the `window.URL.revokeObjectURL()` (en-US) method, passing in the object URL string as specified by `img.src`. 6. Append the new list item to the list. 範例:上傳檔案 ------- 接下來這個範例顯示如何非同步的上傳檔案到伺服器。 ### 新增上傳的工作 接續先前創建縮圖的範例,將每個縮圖都設置 CSS class 「obj」, 這使得我們可以很容易地使用`Document.querySelectorAll()` (en-US) 選擇使用者要上傳的圖檔,例如: ```js function sendFiles() { var imgs = document.querySelectorAll(".obj"); for (var i = 0; i < imgs.length; i++) { new FileUpload(imgs[i], imgs[i].file); } } ``` 第二行創建了 `imgs` 陣列,存放著所有文件中 CSS class 為 「obj」 的 Node。在這個範例中,我們使用這個來創建縮圖。Once we have that list, it's trivial to go through the list, creating a new `FileUpload` instance for each. Each of these handles uploading the corresponding file. ### 處理上傳檔案的程序 `FileUpload` 函數接受圖檔和檔案. ```js function FileUpload(img, file) { var reader = new FileReader(); this.ctrl = createThrobber(img); var xhr = new XMLHttpRequest(); this.xhr = xhr; var self = this; this.xhr.upload.addEventListener( "progress", function (e) { if (e.lengthComputable) { var percentage = Math.round((e.loaded \* 100) / e.total); self.ctrl.update(percentage); } }, false, ); xhr.upload.addEventListener( "load", function (e) { self.ctrl.update(100); var canvas = self.ctrl.ctx.canvas; canvas.parentNode.removeChild(canvas); }, false, ); xhr.open( "POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php", ); xhr.overrideMimeType("text/plain; charset=x-user-defined-binary"); reader.onload = function (evt) { xhr.sendAsBinary(evt.target.result); }; reader.readAsBinaryString(file); } ``` `FileUpload()` 函數創建被用來顯示上傳進度的 throbber,接著創建 `XMLHttpRequest` 上傳檔案. 傳輸資料前的幾個準備工作: 1. The `XMLHttpRequest`'s upload "progress" listener is set to update the throbber with new percentage information, so that as the upload progresses, the throbber will be updated based on the latest information. 2. The `XMLHttpRequest`'s upload "load" event handler is set to update the throbber with 100% as the progress information (to ensure the progress indicator actually reaches 100%, in case of granularity quirks during the process). It then removes the throbber, since it's no longer needed. This causes the throbber to disappear once the upload is complete. 3. The request to upload the image file is opened by calling `XMLHttpRequest`'s `open()` method to start generating a POST request. 4. The MIME type for the upload is set by calling the `XMLHttpRequest` function `overrideMimeType()`. In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all, depending on your use case. 5. The `FileReader` object is used to convert the file to a binary string. 6. Finally, when the content is loaded the `XMLHttpRequest` function `sendAsBinary()` is called to upload the file's content. **備註:** 範例中非標準的 `sendAsBinary` 方法已經在 Gecko 31 廢棄且很快將會被移除。可以改使用標準的 `send(Blob data)。` ### 非同步處理上傳檔案的程序 ```js function fileUpload(file) { // Please report improvements to: marco.buratto at tiscali.it var fileName = file.name, fileSize = file.size, fileData = file.getAsBinary(), // works on TEXT data ONLY. boundary = "xxxxxxxxx", uri = "serverLogic.php", xhr = new XMLHttpRequest(); xhr.open("POST", uri, true); xhr.setRequestHeader( "Content-Type", "multipart/form-data, boundary=" + boundary, ); // simulate a file MIME POST request. xhr.setRequestHeader("Content-Length", fileSize); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) { if (xhr.responseText != "") { alert(xhr.responseText); // display response. } } } }; var body = "--" + boundary + "\r\n"; body += "Content-Disposition: form-data; name='fileId'; filename='" + fileName + "'\r\n"; body += "Content-Type: application/octet-stream\r\n\r\n"; body += fileData + "\r\n"; body += "--" + boundary + "--"; xhr.send(body); return true; } ``` *使用二進制數據時,這些程式碼還需要修改。* 參見 -- * `File` * `FileList` * `FileReader` * 使用 XMLHttpRequest * Using the DOM File API in chrome code * `XMLHttpRequest`
URL.createObjectURL() - Web APIs
URL.createObjectURL() ===================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 摘要 -- 靜態方法 **`URL.createObjectURL()`** 用於建立一個帶有 URL 的 `DOMString` 以代表參數中所傳入的物件. 該 URL 的生命週期與創造它的 window 中的 `document` (en-US)一致. 這個新的物件 URL 代表了所指定的 `File` 物件 或是 `Blob` 物件。 **備註:** 此功能可在 Web Worker (en-US) 中使用 語法 -- ``` objectURL = URL.createObjectURL(blob); ``` 參數 -- *blob* 一個用以建立物件 URL 的 `File` 物件 或是 `Blob` 物件. 範例 -- 參見 Using object URLs to display images.(藉由物件 URL 來顯示圖像) 注意事項 ---- 每次呼叫 `createObjectURL()` 都會產生一個新的 URL, 不論是否曾以同一物件產生過. 當你不再需要它們的時候必須對每一個都呼叫 `URL.revokeObjectURL()` (en-US) 來釋放它們. 瀏覽器會在 document 被 unload 時自動釋放它們; 然而, 為了最佳化效能與記憶體用量, 當有安全的時機請務必手動釋放它們. 規範文件 ---- | Specification | | --- | | File API # dfn-createObjectURL | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 另見 -- * `URL.revokeObjectURL()` (en-US) * Using files from web applications
KeyboardEvent() - Web APIs
KeyboardEvent() =============== **`KeyboardEvent()`** constructor 能用來建立一個新的 `KeyboardEvent`。 語法 -- ``` event = new KeyboardEvent(typeArg, KeyboardEventInit); ``` ### 參數 `type` 一 `DOMString` 用來表示事件名稱。 `options` 選擇性 一個 `KeyboardEventInit` dictionary,能接受以下參數: `key` 選擇性 一個字符串,默認值為 `""`,用來設定 `KeyboardEvent.key` (en-US) 的值。 `code` 選擇性 一個字符串,默認值為 `""`,用來設定 `KeyboardEvent.code` (en-US) 的值。 `location` 選擇性 一個 `unsigned long`,默認值為 `0`,用來設定 `KeyboardEvent.location` (en-US) 的值。 `ctrlKey` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.ctrlKey` (en-US) 的值。 `shiftKey` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.shiftKey` (en-US) 的值。 `altKey` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.altKey` (en-US) 的值。 `metaKey` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.metaKey` (en-US) 的值。 `repeat` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.repeat` (en-US) 的值。 `isComposing` 選擇性 一個 `Boolean`,默認值為 `false`,用來設定 `KeyboardEvent.isComposing` (en-US) 的值。 `charCode` 選擇性 一個 `unsigned long`,默認值為 `0`,用來設定 `KeyboardEvent.charCode` (en-US) 的值。 `keyCode` 選擇性 一個 `unsigned long`,默認值為 `0`,用來設定 `KeyboardEvent.keyCode` (en-US) 的值。 `which` 選擇性 一個 `unsigned long`,默認值為 `0`,用來設定 `KeyboardEvent.which` (en-US) 的值 **備註:** *`KeyboardEventInit` dictionary 亦接受 `UIEventInit` 和`EventInit` 所接受的參數。* 規格 -- | Specification | | --- | | UI Events # dom-keyboardevent-keyboardevent | 瀏覽器支援度 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 延伸閱讀 ---- * `KeyboardEvent` ,此 constructer 所建立的 object 的 interface
FormData.get() - Web APIs
FormData.get() ============== `FormData` 的 **`get()`** 方法會返回 `FormData 物件中,指定` key` 值所對應之第一組物件中的 value 值。然而,如果你想要獲得多組以及全部的 value,那應該使用 `getAll()` (en-US) 方法。 **注意**: 這個方法已可以在 Web Worker (en-US) 中使用。 語法 -- ```js formData.get(name); ``` ### 參數 `name` 一個 `USVString` (en-US),代表你想要得到的 value 所對應的 key 值名稱。 ### 回傳值 A `FormDataEntryValue` (en-US) containing the value. 範例 -- 下面一行程式會產生一個空的 `FormData` 物件: ```js var formData = new FormData(); ``` 用 `FormData.append` (en-US) 方法新增兩組 `username` 值 ```js formData.append("username", "Chris"); formData.append("username", "Bob"); ``` 接下來使用 `get()` 方法,將只會返回上一步驟,第一組新增的 `username` 所對應的值 ```js formData.get("username"); // 返回 "Chris" ``` 規範 -- | Specification | | --- | | XMLHttpRequest Standard # dom-formdata-get | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `XMLHTTPRequest` * 使用 XMLHttpRequest * 使用 FormData 物件 * `<form>` (en-US)
MediaSource.readyState - Web APIs
MediaSource.readyState ====================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 `MediaSource` 介面的唯讀屬性 **`readyState`** 回傳表示當前 `MediaSource` 狀態的列舉值。三種可能的值為: * `closed`: 來源 (source) 目前沒有附加到媒體元件 (media element) 。 * `open`: 來源已經附加且可以接收 `SourceBuffer` (en-US) 物件。 * `ended`: 來源已經附加但是串流已經經由 `MediaSource.endOfStream()` (en-US) 結束。 語法 -- ```js var myReadyState = mediaSource.readyState; ``` ### 回傳值 一個 `DOMString`。 範例 -- 以下片段是由 Nick Desaulniers 所撰寫的簡單範例(在此實際觀看,或者下載原始碼以更進一步研究) ```js if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource(); //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener("sourceopen", sourceOpen); } else { console.error("Unsupported MIME type or codec: ", mimeCodec); } function sourceOpen(\_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener("updateend", function (\_) { mediaSource.endOfStream(); video.play(); //console.log(mediaSource.readyState); // ended }); sourceBuffer.appendBuffer(buf); }); } ``` 規格 -- | Specification | | --- | | Media Source Extensions™ # dom-mediasource-readystate | 相容性表格 ----- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資料 ---- * `SourceBuffer` (en-US) * `SourceBufferList` (en-US)
MediaSource.duration - Web APIs
MediaSource.duration ==================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 `MediaSource` 介面的 **`duration`** 屬性用來取得以及設置正被表示的媒體時間長度。 語法 -- ```js mediaSource.duration = 5.5; // 5.5 seconds var myDuration = mediaSource.duration; ``` ### 回傳值 單位為秒的 double 型別。 ### 錯誤 當設置此屬性一個新的值時以下錯誤可能發生。 | 錯誤 | 解釋 | | --- | --- | | `InvalidAccessError` | 嘗試設置的時間長度是負值,或者 `NaN`。 | | `InvalidStateError` | `MediaSource.readyState` 不是 `open`,或者 `MediaSource.sourceBuffers` (en-US) 中一個或多個以上的 `SourceBuffer` (en-US) 物件正在被更新(例如:他們的 `SourceBuffer.updating` (en-US) 屬性為 `true`。) | 範例 -- 以下的片段基於 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼以利更進一步研究。) ```js function sourceOpen (\_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (\_) { mediaSource.endOfStream(); mediaSource.duration = 120; video.play(); //console.log(mediaSource.readyState); // ended }); sourceBuffer.appendBuffer(buf); }); }; ... ``` 規格 -- | Specification | | --- | | Media Source Extensions™ # dom-mediasource-duration | 相容性表格 ----- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資料 ---- * `SourceBuffer` (en-US) * `SourceBufferList` (en-US)
MediaSource.activeSourceBuffers - Web APIs
MediaSource.activeSourceBuffers =============================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 **`activeSourceBuffers`** 是 `MediaSource` 介面的唯讀屬性,回傳一個 `SourceBufferList` (en-US) 物件,含有在 `SourceBuffers` 之中的 `SourceBuffer` (en-US) 物件子集合—物件的串列提供被選擇的影片軌 (video track), 啟用的音軌 (audio tracks), 以及顯示或隱藏的字軌。 語法 -- ```js var myActiveSourceBuffers = mediaSource.activeSourceBuffers; ``` ### 回傳值 一個 `SourceBufferList` (en-US) 。 範例 -- 以下的片段基於 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼 以利更進一步研究。) ```js function sourceOpen (\_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (\_) { mediaSource.endOfStream(); console.log(mediaSource.activeSourceBuffers); // will contain the source buffer that was added above, // as it is selected for playing in the video player video.play(); //console.log(mediaSource.readyState); // ended }); sourceBuffer.appendBuffer(buf); }); }; ... ``` 規格 -- | Specification | | --- | | Media Source Extensions™ # dom-mediasource-activesourcebuffers | 相容性表格 ----- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資料 ---- * `SourceBuffer` (en-US) * `SourceBufferList` (en-US)
MediaSource.MediaSource() - Web APIs
MediaSource.MediaSource() ========================= **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 `MediaSource` 介面的 **`MediaSource()`** 建構子建構且回傳一個沒有與任何來源緩衝 (source buffer) 關聯的新 `MediaSource` 物件。 語法 -- ```js var mediaSource = new MediaSource(); ``` ### 參數 無。 範例 -- 以下的片段擷取自 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼 以利更進一步研究。) ```js var video = document.querySelector('video'); var assetURL = 'frag\_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag\_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource; //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } ... ``` 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資料 ---- * `SourceBuffer` (en-US) * `SourceBufferList` (en-US)
Screen.orientation - Web APIs
Screen.orientation ================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 `Screen.orientation` 屬性可以取得螢幕目前的方向。 語法 -- ``` var orientation = window.screen.orientation.type; ``` 回傳值 --- 回傳值為一個代表螢幕方向的字串,可能是 `portrait-primary`、`portrait-secondary`、`landscape-primary` 或 `landscape-secondary`(請參考 `lockOrientation` 以瞭解更多資訊)。 範例 -- ```js var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; if (orientation.type === "landscape-primary") { console.log("That looks good."); } else if (orientation.type === "landscape-secondary") { console.log("Mmmh... the screen is upside down!"); } else if ( orientation.type === "portrait-secondary" || orientation.type === "portrait-primary" ) { console.log("Mmmh... you should rotate your device to landscape"); } ``` 規範 -- | Specification | | --- | | Screen Orientation # dom-screen-orientation | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Screen.orientation` * `Screen.unlockOrientation()` (en-US) * `Screen.onorientationchange` (en-US) * 控制畫面方向
PositionError.code - Web APIs
PositionError.code ================== **`PositionError.code`** 是一個唯讀無符號整數(`unsigned short`)表示錯誤碼。以下列出可能的值: | 值 | 相對應的常數 | 描述 | | --- | --- | --- | | `1` | `PERMISSION_DENIED` | 取得地理資訊失敗,因為此頁面沒有獲取地理位置信息的權限。 | | `2` | `POSITION_UNAVAILABLE` | 取得地理資訊失敗,因為至少有一個地理位置信息內的資訊回傳了錯誤。 | | `3` | `TIMEOUT` | 取得地理資訊超過時限,利用 `PositionOptions.timeout` i 來定義取得地理資訊的時限。 | 語法 -- ``` typeErr = poserr.code ``` 規格 -- | Specification | | --- | | Geolocation API # code-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `PositionError` 。
PositionError.message - Web APIs
PositionError.message ===================== **`PositionError.message`** 是一個可讀的 `DOMString` 來描述錯誤的詳細訊息。 語法 -- ``` msg = positionError.message ``` 規格 -- | Specification | | --- | | Geolocation API # message-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `PositionError`。
DragEvent.dataTransfer - Web APIs
DragEvent.dataTransfer ====================== **`DataEvent.dataTransfer`** 屬性保留了拖曳操作中的資料(指向一個 `DataTransfer` (en-US) 物件)。 此屬性為 Read only 。 語法 -- ``` var data = dragEvent.dataTransfer; ``` ### 回傳值 `data` 一個保存 `DragEvent` 當中資料的 `DataTransfer` (en-US) 物件。 範例 -- This example illustrates accessing the drag and drop data within the `dragend` (en-US) event handler. ```js function process\_data(d) { // Process the data ... } dragTarget.addEventListener( "dragend", function (ev) { // Call the drag and drop data processor if (ev.dataTransfer != null) process\_data(ev.dataTransfer); }, false, ); ``` 規範 -- | Specification | | --- | | HTML Standard # dom-dragevent-datatransfer-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Console.assert() - Web APIs
Console.assert() ================ 如果斷言(assertion)為非(false),主控台會顯示錯誤訊息;如果斷言為是(true),則不發生任何事。 **備註:** 此功能可在 Web Worker (en-US) 中使用 **備註:** 在 Node.js 內 `console.assert()` 方法的實做,與瀏覽器並不相同。瀏覽器內呼叫 falsy 的 `console.assert()` 斷言出現 `message`,但不會中斷程式碼的執行。然而在 Node.js 裡面,falsy 斷言會拋出 `AssertionError` 錯誤。 語法 -- ```js assert(assertion, obj1) assert(assertion, obj1, obj2) assert(assertion, obj1, obj2, /\* …, \*/ objN) assert(assertion, msg) assert(assertion, msg, subst1) assert(assertion, msg, subst1, /\* …, \*/ substN) ``` ### 參數 `assertion` 布林表達式。如果斷言為非,訊息會出現在主控台上。 `obj1` ... `objN` 要印出來的 JavaScript 物件名單。 The string representations of each of these objects are appended together in the order listed and output. `msg` 包含零個以上的 JavaScript 替代(substitution)字串。 `subst1` ... `substN` JavaScript objects with which to replace substitution strings within `msg`. This parameter gives you additional control over the format of the output. 請參見 `console` (en-US) 的 Outputting text to the console (en-US) 以獲取詳細資訊。 範例 -- 以下程式碼示範一個 JavaScript 物件的斷言使用: ```js const errorMsg = "the # is not even"; for (let number = 2; number <= 5; number += 1) { console.log("the # is " + number); console.assert(number % 2 === 0, { number: number, errorMsg: errorMsg }); // or, using ES2015 object property shorthand: // console.assert(number % 2 === 0, {number, errorMsg}); } // output: // the # is 2 // the # is 3 // Assertion failed: {number: 3, errorMsg: "the # is not even"} // the # is 4 // the # is 5 // Assertion failed: {number: 5, errorMsg: "the # is not even"} ``` 請注意,雖然包含替換字符串的字符串在 Node 中用作 `console.log` 的參數,但很多(如果不是大多數)瀏覽器... ```js console.log("the word is %s", "foo"); // output: the word is foo ``` ...在所有瀏覽器中,使用此類字符串目前無法作為 console.assert 的參數使用: ```js console.assert(false, "the word is %s", "foo"); // correct output in Node (e.g. v8.10.0) and some browsers // (e.g. Firefox v60.0.2): // Assertion failed: the word is foo // incorrect output in some browsers // (e.g. Chrome v67.0.3396.87): // Assertion failed: the word is %s foo ``` 有關詳細信息,請參閱 `console` (en-US) 文檔中的將文本輸出到控制台 (en-US)。 規範 -- | Specification | | --- | | Console Standard # assert | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * WHATWG Console Standard: console.assert * Opera Dragonfly documentation: Console * MSDN: Using the F12 Tools Console to View Errors and Status * Chrome Developer Tools: Using the Console
HTMLMediaElement: ratechange - Web APIs
HTMLMediaElement: ratechange ============================ `ratechange` 事件將在播放速度改變時被觸發 基本資訊 ---- 規格 HTML5 Media 介面 事件 是否冒泡 否 是否可取消 否 目標 元素 預設行為 無 屬性 -- | 屬性 | 類型 | 描述 | | --- | --- | --- | | `target` Read only | `EventTarget` | 事件目標(DOM 樹中最頂層的目標) | | `type` Read only | `DOMString` | 事件類型 | | `bubbles` Read only | `Boolean` | 事件是否觸發冒泡 | | `cancelable` Read only | `Boolean` | 事件是否可取消 | 規範 -- | Specification | | --- | | HTML Standard # event-media-ratechange | | HTML Standard # handler-onratechange | 相關事件 ---- * `playing` (en-US) * `waiting` (en-US) * `seeking` (en-US) * `seeked` (en-US) * `ended` (en-US) * `loadedmetadata` (en-US) * `loadeddata` (en-US) * `canplay` (en-US) * `canplaythrough` (en-US) * `durationchange` (en-US) * `timeupdate` (en-US) * `play` (en-US) * `pause` (en-US) * `ratechange` * `volumechange` (en-US) * `suspend` (en-US) * `emptied` (en-US) * `stalled` (en-US)
HTMLMediaElement.readyState - Web APIs
HTMLMediaElement.readyState =========================== **`HTMLMediaElement.readyState`** 屬性回傳目前媒體的就緒狀態。 語法 -- ``` var readyState = audioOrVideo.readyState; ``` ### 值 一個 `unsigned short`,可能的值有: | 常數 | 值 | 描述 | | --- | --- | --- | | HAVE\_NOTHING | 0 | 沒有可用的媒體資源。 | | HAVE\_METADATA | 1 | 已經取得足夠的媒體資源並已初始化元資料。繼續取得媒體資源不會導致例外。 | | HAVE\_CURRENT\_DATA | 2 | 媒體資料已經足夠播放目前的時間,但沒有足夠的資料再播放一幀。 | | HAVE\_FUTURE\_DATA | 3 | 資料已經足夠播放目前的時間,而且有至少一點點資料可以播放未來的時間(換句話說,可能只多了一到兩幀)。 | | HAVE\_ENOUGH\_DATA | 4 | 資料足夠,且下載率夠高。媒體可以播放到結束而不被中斷。 | 範例 -- 下面這個例子會監聽 `example` 這個元素,並檢查是否已載入足夠的媒體資源。如果是的話,它會繼續播放。 ```html <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> ``` ```js var obj = document.getElementById("example"); obj.addEventListener("loadeddata", function () { if (obj.readyState >= 2) { obj.play(); } }); ``` 標準 -- | Specification | | --- | | HTML Standard # dom-media-readystate-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 也參考看看 ----- * The interface defining it, `HTMLMediaElement` (en-US).
abort - Web APIs
abort ===== 當資源載入被拒絕時將會觸發\*\*`abort`\*\*事件。 一般資訊 ---- 規範 DOM L3 介面 若由使用者介面產生,為 UIEvent,否則為 Event。 是否向上(冒泡) 否 是否為可取消 否 目標對象 Element 預設行為 無 屬性 -- | 屬性 | 型態 | 描述 | | --- | --- | --- | | `target` Read only | `EventTarget` | 事件的目標對象 (DOM 樹中最頂層的對象)。 | | `type` Read only | `DOMString` | 事件的型態。 | | `bubbles` Read only | `Boolean` (en-US) | 事件是否向上冒泡。 | | `cancelable` Read only | `Boolean` (en-US) | 事件是否能夠取消。 | | `view` Read only | `WindowProxy` | `document.defaultView` (該文檔(Document)的`window`) | | `detail` Read only | `long` (`float`) | 0. | 規範 -- | Specification | | --- | | HTML Standard # event-media-abort | | HTML Standard # handler-onabort |
Canvas 教學文件 - Web APIs
Canvas 教學文件 =========== **`<canvas>`** 是一個 HTML 元素,我們可以利用程式腳本在這個元素上繪圖(通常是用 JavaScript)。除了繪圖,我們還可以合成圖片或做一些簡單(或是不那麼簡單)的動畫。右方的影像便是一些運用 <canvas> 的例子,接下來我們將會在教學文件中一一說明。 本教學從基礎知識開始,描述如何利用 <canvas> 進行 2D 繪圖。教學中的範例會讓各位清楚瞭解 <canvas> 該如何運用,另外也會提供程式碼範例,讓大家嘗試製作自己的內容。 `<canvas>` 最早是由 Apple 為 Mac OS X Dashboard 所提出,之後 Safari 和 Google Chrome 也都採用。Gecko 1.8 作基礎的瀏覽器,如 Firefox 1.5 也都提供了支援。`<canvas>` 元素是 WhatWG Web applications 1.0(也就是 HTML5)規範的一部分,目前所有主流的瀏覽器都已支援。 在開始之前 ----- `<canvas>` 並不困難,但你需要了解基本的 HTML 與 JavaScript。部分舊版瀏覽器不支援 `<canvas>`,不過基本上現今所有主流的瀏覽器都有支援。預設的畫布大小是 300px \* 150px(寬 \* 高)。但你也可以透過 HTML 寬、高屬性(attribute)自訂。為了在畫布上作畫,我們使用了一個 JavaScript context 物件來即時繪製圖形。 教學文件 ---- * 基本用途 * 繪製圖形 * 套用樣式與顏色 * 繪製文字 * 使用影像 * 變形效果 * 合成效果 * 基礎動畫 (en-US) * 進階動畫 * 像素控制 * Hit regions and accessibility * 最佳化 canvas (en-US) * Finale (en-US) 參見 -- * Canvas topic page * Adobe Illustrator to Canvas plug-in * HTML5CanvasTutorials * 31 days of canvas tutorials * Drawing Graphics with Canvas (en-US) * Canvas examples * HTML5 Tutorial * Drawing Text Using a Canvas * Adding Text to Canvas * Canvas Demos - Games, applications, tools and tutorials * Canvas Drawing and Animation Application * interactive canvas tutorial * Canvas Cheat Sheet with all attributes and methods * Adobe Illustrator to Canvas plug-in * HTML5CanvasTutorials * How to draw N grade Bézier curves with the Canvas API * 31 days of canvas tutorials * W3C Standard 致歉各位貢獻者 ------- 由於 2013/6/17 那一週的不幸技術錯誤,所有有關本教學的歷史紀錄,包括過去所有貢獻者的紀錄都遺失了,我們深感抱歉,希望各位可以原諒這一次不幸的意外。 * 次頁 »
使用影像 - Web APIs
使用影像 ==== * « 前頁 * 次頁 » 使用影像是`<canvas>`另一個有趣的功能,這個功能可以用來動態組合圖片或作為背景等等。任何瀏覽器支援的外部圖片格式都可以使用,例如 PNG, GIF, 或 JPEG,甚至也可以利用同一份頁面上其他畫布元素產生的影像. 載入影像到畫布中基本上需要兩個步驟: 1. 取得`HTMLImageElement` (en-US)物件或其他畫布元素的參照(reference)作為來源,透過單純提供 URL 或圖片位置的方式是行不通的. 2. 用 drawImage()函數在畫布上畫影像. 接下來便來看看要怎麼做. 取得影像 ---- 畫布 API 能接受以下資料型態作為影像來源: `HTMLImageElement` (en-US) 用 Image()建構成的影像或是`<img>` (en-US)元素. `HTMLVideoElement` (en-US) 用`HTMLVideoElement` (en-US)元素作影像來源,抓取影片目前的影像畫格當作影像使用. `HTMLCanvasElement` (en-US) 用另一個`HTMLCanvasElement` (en-US)元素當影像來源. `ImageBitmap` (en-US) 可以被快速渲染的點陣圖(bitmap),點陣圖能由上述所有來源產生. 這些來源統一參照 CanvasImageSource型態. 有好幾種方法能夠取得影像用於畫布. ### 使用同一份網頁上的影像 我們能透過下面幾個方法取得影像: * 從`document.images` (en-US) * `document.getElementsByTagName()` (en-US)方法 * 如果知道特定影像的 ID,那可以`document.getElementById()` (en-US)方法 ### 使用來自其他網域的影像 Using the `crossOrigin` (en-US) attribute on an 透過`<htmlimageelement>`的`crossOrigin` (en-US)屬性, 我們可以要求從另一個網域載入影像來使用,若是寄存網域(thehosting domain)准許跨網路存取該影像,那麼我們便可以使用它而不用污染(taint)我們的畫布,反之,使用該影像會污染畫布(taint the canvas (en-US))。 ### 使用其他畫布元素 如同取得其他影像,我們一樣能用`document.getElementsByTagName()` (en-US)或`document.getElementById()` (en-US)方法取得其他畫布元素,但是在使用之前請記得來源畫布上已經有繪上圖了。 使用其他畫布元素作為影像來源有很多有用的應用用途,其中之一便是建立第二個小畫布作為另一個大畫布的縮小影像. ### 創造全新的影像 產生新的`HTMLImageElement` (en-US)物件也能當作影像來源,這邊,我們可以用 Image()來建構一個新影像元素: ```js var img = new Image(); // Create new img element img.src = "myImage.png"; // Set source path ``` 上述程式碼執行後會載入影像. 在影像載入完成前呼叫 drawImage()不會有任何效果,甚至某些瀏覽器還會拋出例外狀況,所以應該要透過利用載入事件來避免這類問題: ```js var img = new Image(); // Create new img element img.addEventListener( "load", function () { // execute drawImage statements here }, false, ); img.src = "myImage.png"; // Set source path ``` 若是只要載入一份影像,可以用上面的方法,不過當需要載入、追蹤多個影像時,我們就需要更好的方法了,雖然管理多個影像載入已經超出本教學的範疇,然而如果有興趣的話,可以參考JavaScript Image Preloader這份文件. ### 以 data:URL 嵌入影像 另一個載入影像的方法是利用data: url (en-US),透過 data URL 可以直接將影像定義成 Base64 編碼的字串,然後嵌入程式碼之中. ```js var img_src = "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=="; ``` data URL 的好處之一是立即產生影像而不用再和伺服器連線,另一個好處是這樣便能夠將影像包入你的CSS, JavaScript, HTML之中,讓影像更具可攜性. 壞處則是影像將不會被快取起來,而且對大影像來說編碼後的 URL 會很長. ### Using frames from a video 我們還能夠使用`<video>` (en-US)元素中的影片的影片畫格(縱使影片為隱藏),例如,現在我們有一個 ID 為「myvideo」 的`<video>` (en-US)元素: ```js function getMyVideo() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); return document.getElementById("myvideo"); } } ``` 上面的方法會回傳一個`HTMLVideoElement` (en-US)的影像物件,如前所述,這個物件可以被視為 CanvasImageSource 類別的物件來使用。 關於如何利用<video>元素於畫布上的進階說明,可以參考 html5Doctor 的「video + canvas = magic」一文. 影像繪圖 ---- 一旦我們取得來源影像物件的參照(reference),便可以用 drawImage()方法將影像渲染到畫布上,drawImage()方法是一個多載(overload)方法,有數個型態,待會我們會看到這項特性,現在我們先來看 drawImage()最基本的型態: `drawImage(image, x, y)` 從座標點(x, y)開始畫上 image 參數指定的來源影像(CanvasImageSource). ### 範例: 一條簡單的線段影像 這個範例會使用外部影像作為一個小型線圖的背景。利用預先劃好的圖作為背景的話就不用再靠程式來產生背景,如此一來可以顯著地減少程式碼。下面藉由影像物件的 load 事件處理器來處理繪圖作業,其中 drawImage()方法把背景圖片放置在畫布左上角,座標點(0, 0)位置. ``` <html> <body onload="draw();"> <canvas id="canvas" width="180" height="150"></canvas> </body> </html> ``` ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); var img = new Image(); img.onload = function () { ctx.drawImage(img, 0, 0); ctx.beginPath(); ctx.moveTo(30, 96); ctx.lineTo(70, 66); ctx.lineTo(103, 76); ctx.lineTo(170, 15); ctx.stroke(); }; img.src = "backdrop.png"; } ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | 縮放 -- drawImage()的第二個型態增加了兩個新參數,讓我們在畫布上放置影像的同時並縮放影像. `drawImage(image, x, y, width, height)` 當放置影像於畫布上時,會按照參數 width(寬)、height(高)來縮放影像. ### 範例: 排列影像 本例我們會取一張影像作為桌布,然後透過簡單的迴圈來重複縮放、貼上影像於畫布上。在程式碼中,第一個迴圈走一遍每一列,第二個迴圈走一遍每一行,影像則縮小成原始影像的三分之一,50 x 38 像素. **備註:** 過度縮放影像可能會造成影像模糊或產生顆粒感,所以如果影像中有文字需要閱讀,最好不要縮放影像. ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); var img = new Image(); img.onload = function () { for (var i = 0; i < 4; i++) { for (var j = 0; j < 3; j++) { ctx.drawImage(img, j \* 50, i \* 38, 50, 38); } } }; img.src = "rhino.jpg"; } ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | 切割影像 ---- drawImage()第三個型態接受 9 個參數,其中 8 個讓我們從原始影像中切出一部分影像、縮放並畫到畫布上. `drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)` image 參數是來源影像物件,(sx, sy)代表在來源影像中以(sx, sy)座標點作為切割的起始點,sWidth 和 sHeight 代表切割寬和高,(dx, dy)代表放到畫布上的座標點,dWidth 和 dHeight 代表縮放影像至指定的寬和高. ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Using_images/canvas_drawimage.jpg)請參照右圖,前四個參數定義了在來源影像上切割的起始點和切割大小,後四個參數定義了畫到畫布上的位置和影像大小. 切割是一個很有用的工具,我們可以把所有影像放到一張影像上,然後利用切割來組成最終完整的影像,比如說,我們可以把所有需要用來組成一張圖表的文字放到一張 PNG 圖檔內,之後只需要單純地再依據資料來縮放圖表,另外,我們也不用多次載入多張影像,這樣對提升載入影像效能頗有幫助. ### 範例: 畫一個有畫框的影像 本例用和前一個範例一樣的犀牛圖,然後切出犀牛頭部影像部分再放入一個影像畫框,這個影像畫框是一個有陰影的 24 位元 PNG 圖檔,因為 24 位元 PNG 影像具備完整的 8 位元不透明色版(alpha channel),所以不像 GIF 影像和 8 位元 PNG 影像,它能夠放任何背景之上而無須擔心產生消光色(matte color). ```html <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> <div style="display:none;"> <img id="source" src="rhino.jpg" width="300" height="227" /> <img id="frame" src="canvas\_picture\_frame.png" width="132" height="150" /> </div> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // Draw slice ctx.drawImage( document.getElementById("source"), 33, 71, 104, 124, 21, 20, 87, 104, ); // Draw frame ctx.drawImage(document.getElementById("frame"), 0, 0); } ``` 這次我們不產生新的`HTMLImageElement` (en-US)物件,改採用直接把影像包入 HTML 的`<img>` (en-US)標籤,然後再取得影像元素,其中 HTML 上的影像已經透過設定 CSS 屬性`display` (en-US)為 none 來隱藏起來了. | Screenshot | Live sample | | --- | --- | | | | 程式碼相當簡單,每個`<img>` (en-US)有自己的 ID 屬性,這樣便可以利用`document.getElementById()` (en-US)輕易取得,之後再簡單地用 drawImage()方法切割犀牛影像然後縮放並放到畫布上,最後第二個 drawImage()再把畫框放到上面. 畫廊範例 ---- 在本章的最後一個範例,我們將建造一個小畫廊。當網頁載入完成時,我們會為每一張影像產生一個`<canvas>`元素,並且加上畫框. 本範例中,每一張影像的寬高是固定的,畫框也是一樣,你可以嘗試看看改進程式碼,依據影像的寬高來設定畫框,使畫框能剛剛好框住影像. 從下方的程式碼範例可以很清楚看到,我們為`document.images` (en-US)容器內的影像,一張一張地新建畫布,其中,對於不熟悉文件物件模型 (DOM)的人來說,大慨比較值得注意之處在於使用到`Node.insertBefore` (en-US) 方法;insertBefore()是影像元素的父節點(亦即<td>元素)的一個方法,這個方法會把新畫布元素插入於影像元素之前. ```html <html> <body onload="draw();"> <table> <tr> <td><img src="gallery\_1.jpg" /></td> <td><img src="gallery\_2.jpg" /></td> <td><img src="gallery\_3.jpg" /></td> <td><img src="gallery\_4.jpg" /></td> </tr> <tr> <td><img src="gallery\_5.jpg" /></td> <td><img src="gallery\_6.jpg" /></td> <td><img src="gallery\_7.jpg" /></td> <td><img src="gallery\_8.jpg" /></td> </tr> </table> <img id="frame" src="canvas\_picture\_frame.png" width="132" height="150" /> </body> </html> ``` 這些是一些設定樣式的 CSS: ```css body { background: 0 -100px repeat-x url(bg\_gallery.png) #4f191a; margin: 10px; } img { display: none; } table { margin: 0 auto; } td { padding: 15px; } ``` 綜合起來這就是建造出我們小畫廊的程式碼: ```js function draw() { // Loop through all images for (var i = 0; i < document.images.length; i++) { // Don't add a canvas for the frame image if (document.images[i].getAttribute("id") != "frame") { // Create canvas element canvas = document.createElement("canvas"); canvas.setAttribute("width", 132); canvas.setAttribute("height", 150); // Insert before the image document.images[i].parentNode.insertBefore(canvas, document.images[i]); ctx = canvas.getContext("2d"); // Draw image to canvas ctx.drawImage(document.images[i], 15, 20); // Add frame ctx.drawImage(document.getElementById("frame"), 0, 0); } } } ``` 控制影像縮放行為 -------- 如前所述,縮放影像會導致影像模糊化或是顆粒化,你可以嘗試透過繪圖環境的 imageSmoothingEnabled 屬性來控制影像平滑演算法的使用,預設上這個屬性的值為 true,也就是說當縮放時,影像會經過平滑處理。如果要關掉這個功能,你可以這麼做: ```js ctx.mozImageSmoothingEnabled = false; ``` * « 前頁 * 次頁 »
變形效果 - Web APIs
變形效果 ==== * « 前頁 * 次頁 » 畫布狀態儲存與復原 --------- 在使用變形效果等複雜繪圖方法之前,有兩個不可或缺的方法(method)必須要先了解一下: `save()` 儲存現階段畫布完整狀態。 `restore()` 復原最近一次儲存的畫布狀態。 每一次呼叫 save(),畫布狀態便會存進一個堆疊(stack)之中。畫布狀態包含了: * 曾經套用過的變形效果,如 translate, rotate 和 scale(稍後說明)。 * `strokeStyle`, `fillStyle`, `globalAlpha`, `lineWidth`, `lineCap`, `lineJoin`, `miterLimit`, `shadowOffsetX`, `shadowOffsetY`, `shadowBlur`, `shadowColor`, `globalCompositeOperation` 屬性的屬性值 * 目前截圖路徑(稍後說明)。 我們可以呼叫 save()的次數不限,而每一次呼叫 restore(),最近一次儲存的畫布狀態便會從堆疊中被取出,然後還原畫布到此畫布狀態。 ### 畫布狀態儲存與復原範例 本例會畫一連串矩形圖案來說明畫布狀態堆疊是如何運作。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(0, 0, 150, 150); // Draw a rectangle with default settings ctx.save(); // Save the default state ctx.fillStyle = "#09F"; // Make changes to the settings ctx.fillRect(15, 15, 120, 120); // Draw a rectangle with new settings ctx.save(); // Save the current state ctx.fillStyle = "#FFF"; // Make changes to the settings ctx.globalAlpha = 0.5; ctx.fillRect(30, 30, 90, 90); // Draw a rectangle with new settings ctx.restore(); // Restore previous state ctx.fillRect(45, 45, 60, 60); // Draw a rectangle with restored settings ctx.restore(); // Restore original state ctx.fillRect(60, 60, 30, 30); // Draw a rectangle with restored settings } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 預設用黑色填滿這個矩形 每種狀態可以看成是一層層堆疊的步驟紀錄 第一步:畫出黑色矩形 接著把第一個狀態儲存下來(用黑色填滿) 第二步:畫出藍色矩形 接著把第二個狀態儲存下來(用藍色填滿) 第三步:畫出半透明矩形 第四步:再畫出矩形 這時候我們取用最新儲存過的藍色(第二狀態) 第五步:再畫一個矩形 我們再取出更早之前儲存的黑色(第一狀態) | Screenshot | Live sample | | --- | --- | | | | 移動畫布 ---- ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Transformations/canvas_grid_translate.png)第一個變形效果方法是 translate()。translate()是用來移動畫布,如右圖,原先畫布的原點在網格(0, 0)位置,我們可以移動畫布,使其原點移到(x, y)位置。 `translate(x, y)` 移動網格上的畫布,其中 x 代表水平距離、y 代表垂直距離。 最好在做任何變形效果前先儲存一下畫布狀態,如此當我們需要復原先前的狀態時,只需要呼叫一下 restore()即可,而且有一種情況是當我們在迴圈中移動畫布,如果不記得儲存和回復畫布狀態,繪圖區域很容易最後就超出邊界,然後出現圖案不見的狀況。 ### 移動畫布範例 下面程式碼示範了利用 translate()畫圖的好處,裡面,我們用了 drawSpirograph()函數畫萬花筒類的圖案,如果沒有移動畫布原點,那麼每個圖案只會有四分之一會落在可視範圍,藉由移動畫布原點我們便可以自由變換每個圖案的位置,使圖案完整出現,而且省去手動計算調整每個圖案的座標位置。 另外一個 draw()函數透過兩個 for 迴圈移動畫布原點、呼叫 drawSpirograph()函數、復歸畫布圓點位置共九次。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(0, 0, 300, 300); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ctx.save(); ctx.strokeStyle = "#9CFF00"; ctx.translate(50 + j \* 100, 50 + i \* 100); drawSpirograph( ctx, (20 \* (j + 2)) / (j + 1), (-8 \* (i + 3)) / (i + 1), 10, ); ctx.restore(); } } } function drawSpirograph(ctx, R, r, O) { var x1 = R - O; var y1 = 0; var i = 1; ctx.beginPath(); ctx.moveTo(x1, y1); do { if (i > 20000) break; var x2 = (R + r) \* Math.cos((i \* Math.PI) / 72) - (r + O) \* Math.cos(((R + r) / r) \* ((i \* Math.PI) / 72)); var y2 = (R + r) \* Math.sin((i \* Math.PI) / 72) - (r + O) \* Math.sin(((R + r) / r) \* ((i \* Math.PI) / 72)); ctx.lineTo(x2, y2); x1 = x2; y1 = y2; i++; } while (x2 != R - O && y2 != 0); ctx.stroke(); } ``` ``` <canvas id="canvas" width="300" height="300"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | 旋轉 -- ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Transformations/canvas_grid_rotate.png)rotate()函數可以畫布原點作中心,旋轉畫布。 `rotate(x)` 以畫布原點為中心,順時針旋轉畫布 x 弧度(弧度 = Math.PI \* 角度 / 180)。 我們可以呼叫 translate()方法來移動旋轉中心(亦即畫布原點)。 ### 旋轉範例 本範例我們呼叫 rotate()方法來畫一系列環狀圖案。如果不用 rotate(),同樣的效果也可以藉由個別計算 x, y 座標點(x = r\*Math.cos(a); y = r\*Math.sin(a))達成;呼叫 rotate()和個別計算 x, y 座標點不同之處在於,個別計算 x, y 座標點只有旋轉圓形圓心,而圓形並沒有旋轉,呼叫 rotate()則會旋轉圓形和圓心,不過因為我們的圖案是圓形,所以兩種作法產生的效果不會有差異。 我們執行了兩個迴圈來作圖,第一個迴圈決定的圓環個數和該圓環上圓環上圓點的個數的顏色,第二個迴圈決定了圓環上圓點的個數,每一次作圖前我們都儲存了原始畫布狀態,以便結束時可以復原狀態。畫布旋轉的弧度則以圓環上圓點的個數決定,像是最內圈的圓環共有六個圓點,所以每畫一個原點,畫布就旋轉 60 度(360 度/6),第二的圓環有 12 個原點,所以畫布一次旋轉度數為 30 度(360 度/12),以此類推。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.translate(75, 75); for (var i = 1; i < 6; i++) { // Loop through rings (from inside to out) ctx.save(); ctx.fillStyle = "rgb(" + 51 \* i + "," + (255 - 51 \* i) + ",255)"; for (var j = 0; j < i \* 6; j++) { // draw individual dots ctx.rotate((Math.PI \* 2) / (i \* 6)); ctx.beginPath(); ctx.arc(0, i \* 12.5, 5, 0, Math.PI \* 2, true); ctx.fill(); } ctx.restore(); } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | 縮放 -- 接下來這一個變形效果為縮放圖形。 scale(x, y) x 代表縮放畫布水平網格單位 x 倍,y 代表縮放畫布垂直網格單位 y 倍,輸入 1.0 不會造成縮放。如果輸入負值會造成座標軸鏡射,假設輸入 x 為-1,那麼原本畫布網格 X 軸上的正座標點都會變成負座標點、負座標點則變成正座標點。 只要利用 scale(),我們可以建立著名的笛卡兒座標系;執行 translate(0,canvas.height)先移動畫布原點到左下角,再執行 scale(1,-1)顛倒 Y 軸正負值,一個笛卡兒座標系便完成了。 預設上畫布網格前進一單位等於前進一像素大小,所以縮小 0.5 倍,就會變成前進 0.5 的像素大小,亦即縮小圖像一半大小,反之,放大 2 倍將放大圖像 2 倍。 ### 縮放範例 本程式碼範例會畫出一系列不同縮放比例的萬花筒樣式圖案。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.strokeStyle = "#fc0"; ctx.lineWidth = 1.5; ctx.fillRect(0, 0, 300, 300); // Uniform scaling ctx.save(); ctx.translate(50, 50); drawSpirograph(ctx, 22, 6, 5); ctx.translate(100, 0); ctx.scale(0.75, 0.75); drawSpirograph(ctx, 22, 6, 5); ctx.translate(133.333, 0); ctx.scale(0.75, 0.75); drawSpirograph(ctx, 22, 6, 5); ctx.restore(); // Non uniform scaling (y direction) ctx.strokeStyle = "#0cf"; ctx.save(); ctx.translate(50, 150); ctx.scale(1, 0.75); drawSpirograph(ctx, 22, 6, 5); ctx.translate(100, 0); ctx.scale(1, 0.75); drawSpirograph(ctx, 22, 6, 5); ctx.translate(100, 0); ctx.scale(1, 0.75); drawSpirograph(ctx, 22, 6, 5); ctx.restore(); // Non uniform scaling (x direction) ctx.strokeStyle = "#cf0"; ctx.save(); ctx.translate(50, 250); ctx.scale(0.75, 1); drawSpirograph(ctx, 22, 6, 5); ctx.translate(133.333, 0); ctx.scale(0.75, 1); drawSpirograph(ctx, 22, 6, 5); ctx.translate(177.777, 0); ctx.scale(0.75, 1); drawSpirograph(ctx, 22, 6, 5); ctx.restore(); } function drawSpirograph(ctx, R, r, O) { var x1 = R - O; var y1 = 0; var i = 1; ctx.beginPath(); ctx.moveTo(x1, y1); do { if (i > 20000) break; var x2 = (R + r) \* Math.cos((i \* Math.PI) / 72) - (r + O) \* Math.cos(((R + r) / r) \* ((i \* Math.PI) / 72)); var y2 = (R + r) \* Math.sin((i \* Math.PI) / 72) - (r + O) \* Math.sin(((R + r) / r) \* ((i \* Math.PI) / 72)); ctx.lineTo(x2, y2); x1 = x2; y1 = y2; i++; } while (x2 != R - O && y2 != 0); ctx.stroke(); } ``` ``` <canvas id="canvas" width="300" height="300"></canvas> ``` ``` draw(); ``` 第一排第一個黃色圖案是沒有縮放的圖案,然後往右到了第二個圖案,我們程式碼中輸入了 (0.75, 0.75)的縮放倍率,到了第三個圖案,我們還是輸入了 (0.75, 0.75)的縮放倍率,而基於之前有縮小過一次,所以第三個圖案相對於第一個沒有縮放的圖案是 0.75 × 0.75 = 0.5625 倍。 第二排藍色圖案我們只改變 Y 軸的縮放倍率,X 軸維持不變,因而產生一個比一個更扁的橢圓圖形。同理,第三排綠色圖案改變 X 軸的縮放倍率,Y 軸維持不變。 | Screenshot | Live sample | | --- | --- | | | | 變形 -- 最後一個方法是設定變形矩陣,藉由改變變形矩陣,我們因此可以營造各種變形效果;其實先前所提到的 rotate, translate, scale 都是在設定變形矩陣,而這邊的這個方法就是直接去改變變形矩陣。 `transform(m11, m12, m21, m22, dx, dy)` 呼叫 Transform 會拿目前的變形矩陣乘以下列矩陣:`plain m11 m21 dx m12 m22 dy 0 0 1` 運算後的新矩陣將取代目前的變形矩陣。其中 m11 代表水平縮放圖像,m12 代表水平偏移圖像,m21 代表垂直偏移圖像,m22 代表垂直縮放圖像,dx 代表水平移動圖像,dy 代表垂直移動圖像。如果輸入`Infinity` 值,不會引起例外錯誤,矩陣值會依照輸入設成無限。 `setTransform(m11, m12, m21, m22, dx, dy)` 復原目前矩陣為恆等矩陣(Identiy matrix,也就是預設矩陣),然後再以輸入參數呼叫 transform()。 ### `transform` / `setTransform` 範例 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); var sin = Math.sin(Math.PI / 6); var cos = Math.cos(Math.PI / 6); ctx.translate(100, 100); var c = 0; for (var i = 0; i <= 12; i++) { c = Math.floor((255 / 12) \* i); ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")"; ctx.fillRect(0, 0, 100, 10); ctx.transform(cos, sin, -sin, cos, 0, 0); } ctx.setTransform(-1, 0, 0, 1, 100, 100); ctx.fillStyle = "rgba(255, 128, 255, 0.5)"; ctx.fillRect(0, 50, 100, 100); } ``` ``` <canvas id="canvas" width="200" height="250"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | * « 前頁 * 次頁 »
使用canvas繪製文字 - Web APIs
使用canvas繪製文字 ============ * « 前頁 * 次頁 » `canvas`元素支援在標準 HTML 5 特色以及少許實驗性的 Mozilla 方法和功能上繪製文字。 文字可以包括任何 Unicode 字元,即使用那些超出「基本多文種平面」的字元也可以。 方法概述 ---- | | | --- | | `void fillText(in DOMString text, in float x, in float y, [optional] in float maxWidth);` | | nsIDOMTextMetrics `measureText(in DOMString textToMeasure);` | | `void mozDrawText(in DOMString textToDraw); 已棄用` | | `float mozMeasureText(in DOMString textToMeasure);` `已棄用` | | `void mozPathText(in DOMString textToPath);` | | `void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);` | | `void strokeText(in DOMString text, in float x, in float y, [optional] in float maxWidth);` | 屬性 -- | | | | | --- | --- | --- | | 屬性 | 型別 | 描述 | | `font` | `DOMString` | 當前的文字樣式被用在繪製文字。該字串使用和 CSS font(樣式表字型)相同的語法。要改變繪製文字的樣式,只要簡單的改變它的屬性值即可,就像下面展示的,預設的字型是10px(像素) sans-serif(字型名稱) 例如: ``` ctx.font = "20pt Arial"; ``` | | `mozTextStyle` 已棄用 | `DOMString` | 由上面的Html5`字型` 屬性取代 | | `textAlign` | `DOMString` | 當前繪製文字所使用的文字對齊方式。 可使用的值: left 文字靠左對齊。 right 文字靠右對齊。 center 文字置中對齊。 start 文字依照行首對齊 (書寫習慣由左到右的地區就靠左對齊,書寫習慣由右到左的就靠右對齊。). end 文字依照行尾對齊(書寫習慣由左到右的地區就靠右對齊,書寫習責由右到左的地區就靠左對齊。) 預設的值是 `start`. | | `textBaseline` | `DOMString` | 當前繪製文字的基線位置 可使用的值: top 基線在字元區塊的頂部(圖中top of the squre位置)。 hanging(懸掛) 文字基線在拼音文字頂部的位置(圖中hanging baseline) *當前仍未支援;會顯示 **alphabetic**代替。* middle 文字基線在字元區塊的中間。 alphabetic(拼音文字) 這是一般拼音文字底線的位置。 ideographic(表意文字) 文字在表意文字(如漢字)底部的位置 *當前仍未支援;會顯示**alphabetic**代替。* bottom 基線在拼音文字下伸部的位置 這與ideographic的基線位置不同,因為表意文字沒有下伸部 預設使用 `alphabetic`. | 下圖展示了 textBaseline 屬性所支援的各種基線,感謝 WHATWG. ![top of em squre(字元區塊頂部)大致在字型中所有字母的最頂部位置,hanging basline(懸掛基線)則是在一些特殊(較小的,像是「आ」)字母頂部,middle則是在top of em squre(字元區塊頂部和bottom of em squre(字元區塊底部)的中間,alphabetic(拼音文字)的基線位置則是在一般拼音字母如Á,ÿ,f,Ω的底線位置。ideographic(表意文字)的基線在字元的底部位置,bottom of em squre(字元區塊底部)則大致是字型中所有字母的最底部位置。而top and bottom of the bounding box(上下的區域範圍線)則比這些基線都來得更遠,基於字母的高度可能超過字元區塊頂部和底部的範圍。](http://www.whatwg.org/specs/web-apps/current-work/images/baselines.png) 方法 -- ### fillText() 繪製文字使用`font`屬性指定的文字樣式,對齊則使用`textAlign`屬性,而指定基線則使用`textBaseline`. 填充文字當前使用`fillStyle`,而`strokeStyle`則被忽略 **備註:** 這個方法在 Gecko 1.9.1 (Firefox 3.5)時引進,且是 HTML 5 標準的一部分. ``` void fillText( in DOMString textToDraw, in float x, in float y, [optional] in float maxWidth ); ``` ##### 參數 `textToDraw` 將文字繪製到文本中。 `x` 繪製位置的 x 座標。 `y` 繪製位置的 y 座標。 `maxWidth` 最大寬度,可選用的;繪製字串最大長度 如果指定此參數,當字串被計算出比這個值更寬,它會自動選擇水平方向更窄的字型(如果有可用的字型或是有可讀的字型可以嵌入當前字型之中),或者縮小字型。 ##### 範例 ```js ctx.fillText("Sample String", 10, 50); ``` ### measureText() 測量文字。返回一個物件包含了寬度,像素值,所指定的文字會以當前的文字樣式繪製。 **備註:** 這個方法在 Gecko 1.9.1 (Firefox 3.5) 引進,且是 HTML 5 標準的一部分。 ``` nsIDOMTextMetrics measureText( in DOMString textToMeasure ); ``` #### 參數 `textToMeasure` 該字串的像素值。 #### 返回值 `nsIDOMTextMetrics`物件的`width`屬性在繪製時會將數字設定給 CSS 的像素值寬度。 ### mozDrawText() **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 繪製文字使用由`mozTextStyle`屬性的文字樣式。文本當前的填充顏色被用來當做文字顏色。 **備註:** 這個方法已經不被建議使用,請使用正式的 HTML 5 方法 `fillText()` and `strokeText()`. ``` void mozDrawText( in DOMString textToDraw ); ``` #### 參數 `textToDraw` 將文字繪製到文本。 #### 範例 ```js ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozDrawText("Sample String"); ``` 這個範例將文字「Sample String」繪製到畫布(canvas)上。 ### mozMeasureText() **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 返回寬度,像素值,指定文字 **備註:** 這個方法已經已宣告棄用,請使用正式的 HTML 5 方法`measureText()`. ``` float mozMeasureText( in DOMString textToMeasure ); ``` #### 參數 `textToMeasure` 字串的寬度像素值 #### 返回值 文字的寬度像素值 #### 範例 ```js var text = "Sample String"; var width = ctx.canvas.width; var len = ctx.mozMeasureText(text); ctx.translate((width - len) / 2, 0); ctx.mozDrawText(text); ``` 這個範例測量了字串的寬度,接著使用這個資訊將它畫在畫布(canvas)的水平中心。 ### mozPathText() 給文字路徑加上外框線,如果你想要的話,它允許你替文字加上框線代替填充它。 ``` void mozPathText( in DOMString textToPath ); ``` #### 參數 `textToPath` 為當前的文字路徑加上框線 #### Example ```js ctx.fillStyle = "green"; ctx.strokeStyle = "black"; ctx.mozPathText("Sample String"); ctx.fill(); ctx.stroke(); ``` 這個範例繪出文字「Sample String」,填充顏色是綠色,外框顏色是黑色。 ### mozTextAlongPath() Adds (or draws) the specified text along the current path. ``` void mozTextAlongPath( in DOMString textToDraw, in boolean stroke ); ``` #### 參數 `textToDraw` 沿著指定路徑繪出文字 `stroke` 如果參數是 `true`(真值),文字會沿著指定路徑繪製。如果 `false`(假值),這個文字則會加入到路徑之中,再沿著當前路徑繪製。 #### 備註 字體不會沿著路徑曲線縮放或變形,反而在彎曲路徑下,字體每次計算都會當成是直線在處理。這可以用來建立一些特殊的效果。 ### strokeText() 繪製文字使用`font`屬性指定的文字樣式,對齊則使用`textAlign`屬性,而指定基線則使用`textBaseline`. 當前使用`strokeStyle`來建立文字外框。 **備註:** 這個方法在 Gecko 1.9.1 (Firefox 3.5)時引進,且是 HTML 5 標準的一部分。 ``` void strokeText( in DOMString textToDraw, in float x, in float y, [optional] in float maxWidth ); ``` ##### 參數 `textToDraw` 將文字繪製到文本中。 `x` 繪製位置的 x 座標。 `y` 繪製位置的 y 座標 `maxWidth` 最大寬度,可選用的;繪製字串最大長度 如果指定此參數,當字串被計算出比這個值更寬,它會自動選擇水平方向更窄的字型(如果有可用的字型或是有可讀的字型可以嵌入當前字型之中),或者縮小字型。 ##### 範例 ```js ctx.strokeText("Sample String", 10, 50); ``` 備註 -- * 請見 WHATWG specification 關於 HTML 5 canvas text 的說明。 * 你不需要特別的文本來使用這些功能;2D 的文本就可以執行得很好。 * 所有的繪圖都使用即時變化來完成。
最佳化canvas - Web APIs
最佳化canvas ========= `<canvas>`在網頁 2D 繪圖上被大量運用於遊戲和複雜視覺化效果上。隨著繪圖複雜度越來越高,效能問題也會逐一浮現,所以最後我們在這邊列出一些最佳化畫布的方法,避免一些效能問題: * 在畫面之外的畫布上先行渲染相似或重複的物件 * 批次性執行繪圖,例如一次畫數個線條而非分開一次一次畫 * 使用整數位座標值,盡量避免小數點值 * 避免不必要的畫布狀態改變 * 只渲染不同處,不要全部重新渲染 * 對於複雜需求可以利用多個畫布分層構成 * 盡量不要用 shadowBlur 屬性 * 使用`window.requestAnimationFrame()` * 用JSPerf測試效能 * « 前頁 (en-US)
合成效果 - Web APIs
合成效果 ==== * « 前頁 * 次頁 » 在前述的範例中,新繪製的圖形總會覆蓋在之前的圖形上,對大多數情況來說這相當正常,不過它也限制了圖形繪製的順序。其實我們可以透過 globalCompositeOperation 屬性來改變這項預設行為。 `globalCompositeOperation` -------------------------- 利用 globalCompositeOperation,我們可以將新圖形繪製在舊圖形之下、遮蓋部分區域、清除畫布部分區域 (不同於 clearRect() 函式只能清除矩形區域)。 `globalCompositeOperation = type` type 字串可指定為以下 12 種合成設定之一,每一種合成設定均將套用到新繪製的圖形上。 See compositing examples (en-US) for the code of the following examples. 裁剪路徑 ---- ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Compositing/canvas_clipping_path.png)裁剪路徑就像是一般畫布圖形繪圖,但就如同遮罩一樣,會蓋掉不需要的部分,如右圖所示。紅邊星星是我們的裁剪路徑,在路徑區域以外部分都不會出現在畫布上。 和上述 globalCompositeOperation 相比,可以發現 source-in 和 source-atop 這兩種構圖組合所達到的效果,和裁剪路徑類似,而其中最大差異在於裁剪路徑不需加入新圖形,消失的部分也不會出現在畫布上,所以,如果想要限定繪圖區域,裁剪路徑會是更理想的作法。 在繪畫圖形一章中,我們只提到 stroke() 和 fill() 函式,但其實還有第三個函式,那就是 clip() 函式。 `clip()` 轉換目前繪圖路徑為裁剪路徑。 呼叫 clip() 除了會替代 closePath() 來關閉路徑之外,還會轉換目前填滿或勾勒繪圖路徑為裁剪路徑。 `<canvas>` 畫布預設有一個等同於本身大小的裁剪路徑,等同於無裁剪效果。 ### `clip` 範例 本範例使用了圓形的裁剪路徑,來限定畫星星時的繪圖區域。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(0, 0, 150, 150); ctx.translate(75, 75); // Create a circular clipping path ctx.beginPath(); ctx.arc(0, 0, 60, 0, Math.PI \* 2, true); ctx.clip(); // draw background var lingrad = ctx.createLinearGradient(0, -75, 0, 75); lingrad.addColorStop(0, "#232256"); lingrad.addColorStop(1, "#143778"); ctx.fillStyle = lingrad; ctx.fillRect(-75, -75, 150, 150); // draw stars for (var j = 1; j < 50; j++) { ctx.save(); ctx.fillStyle = "#fff"; ctx.translate( 75 - Math.floor(Math.random() \* 150), 75 - Math.floor(Math.random() \* 150), ); drawStar(ctx, Math.floor(Math.random() \* 4) + 2); ctx.restore(); } } function drawStar(ctx, r) { ctx.save(); ctx.beginPath(); ctx.moveTo(r, 0); for (var i = 0; i < 9; i++) { ctx.rotate(Math.PI / 5); if (i % 2 == 0) { ctx.lineTo((r / 0.525731) \* 0.200811, 0); } else { ctx.lineTo(r, 0); } } ctx.closePath(); ctx.fill(); ctx.restore(); } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 一開始我們先畫了一個黑色矩形作為畫布背景,然後移動畫布原點到中央,接著我們繪製弧線並呼叫 clip(),藉以建立圓形的裁剪路徑。畫布儲存狀態亦可儲存裁剪路徑。若要保留原本的裁剪路徑,則可於繪製新的裁剪路徑之前,先行儲存畫布狀態。 繪製裁剪路徑之後,所產生的所有圖形都只會出現在路徑以內,從後來繪製的漸層背景中可看出此特性。我們用自訂的 drawStar() 函數產生 50 個隨機散佈、大小不一的星星。這些星星同樣只會出現在裁剪路徑的範圍之內。 | Screenshot | Live sample | | --- | --- | | | | * « 前頁 * 次頁 » (en-US)
Canvas 基本用途 - Web APIs
Canvas 基本用途 =========== * « 前頁 * 次頁 » Let's start this tutorial by looking at the `<canvas>` HTML element itself. At the end of this page, you will know how to set up a canvas 2D context and have drawn a first example in your browser. `<canvas>` 元素 ------------- ```html <canvas id="tutorial" width="150" height="150"></canvas> ``` 首先,先來看看 `<canvas>`,它看起來有點像 `<img>` (en-US) 元素,其中的差異點在於 `<canvas>` 沒有 `src` 和 `alt` 屬性,`<canvas>` 只有 `width` 與 `height` 這兩個屬性,這兩個屬性皆為非必須、能透過 DOM 屬性設定;若是沒有設定 `width` 和 `height` 屬性,畫布寬預設值為 **300 pixels**、高預設值為 **150 pixels**,我們可以用 CSS 強制設定元素尺寸,但當渲染時,影像會縮放以符合元素的尺寸。 **備註:** 如果繪圖結果看起來有些扭曲,可以改試著用<canvas>自身的 width 和 height 屬性而不要用 CSS 來設定寬高。 幾乎所有 HTML 元素都有 id 屬性,<canvas>也不例外,為了方便於程式碼腳本找到需要的<canvas>,每次都設定 id 是一項不錯的作法。 如同一般的影像可以設定如邊界(margin)、邊框(border)、背景(background)等等,<canvas>元素一樣可以設定這些樣式,然而,這些樣式規則不會影響 canvas 實際繪圖,稍後我們會看到相關範例。當沒有套用樣式規定時,<canvas>會被初始成全透明。 ### 錯誤替代內容(Fallback content) 因為舊版瀏覽器(特別是 IE9 之前的 IE)不支援{<canvas>}元素,我們應該為這些瀏覽器準備錯誤替代內容。 當不支援<canvas>的瀏覽器看到不認識的<canvas>時會忽略<canvas>,而此時在<canvas>下瀏覽器認識的替代內容則會被瀏覽器解析顯示,至於支援<canvas>的瀏覽器則是會正常解析<canvas>,忽略替代內容。 例如,我們可以準備一段 canvas 內容的說明文字或 canvas 繪圖完成後的靜態圖片,如下所示: ```html <canvas id="stockGraph" width="150" height="150"> current stock price: $3.15 +0.15 </canvas> <canvas id="clock" width="150" height="150"> <img src="images/clock.png" width="150" height="150" alt="" /> </canvas> ``` 需要</canvas>標籤 ------------- 不像`<img>` (en-US)元素,`<canvas>`元素必須要有</canvas>結束標籤。 **備註:** 縱使早期 Apple 的 Safari 瀏覽器不需要結束標籤,但是基於規範,這是必須的,所以,為了相容性考量,應該要有結束標籤。Safari 2.0 以前的版本會同時解析 canvas 以及替代內容,除非我們用 CSS 去遮蓋內容,不過幸運的是,現在已經沒有甚麼人在用這些舊版 Safari。 如果不需要錯誤替代內容,簡單的<canvas id="foo" ...></canvas>便可以完全相容於所有支援的瀏覽器。 渲染環境(rendering context) ----------------------- `<canvas>`產生一個固定大小的繪圖畫布,這個畫布上有一或多個渲染環境(rendering context),我們可以用渲染環境來產生或操作顯示內容的渲染環境(rendering context)。不同環境(context)可能會提供不同型態的渲染方式,好比說WebGL (en-US)使用OpenGL ES的 3D 環境(context),而這裡我們主要將討論 2D 渲染環境(rendering context)。 一開始 canvas 為空白,程式碼腳本需要先存取渲染環境,在上面繪圖,然後才會顯現影像。`<canvas>` 素有一個方法 (en-US)叫 getContext(),透過此方法可以取得渲染環境及其繪圖函數(function);getContext() 輸入參數只有渲染環境類型一項,像本教學所討論的 2D 繪圖,就是輸入「2d」。 ```js var canvas = document.getElementById("tutorial"); var ctx = canvas.getContext("2d"); ``` 上面第一行先呼叫`document.getElementById()` (en-US)來取得`<canvas>`元素,一旦取得元素後,便可以用其 getContext()取得渲染環境。 支援性檢查 ----- 替代內容會被不支援`<canvas>`.的瀏覽器所顯示。程式碼腳本也可以利用檢查 getContext()方法是否存在來檢查是否支援<canvas>,我們可以修改上面例子成如下: ```js var canvas = document.getElementById("tutorial"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // drawing code here } else { // canvas-unsupported code here } ``` 一個範本 ---- 這裡是一個最簡單的範本,之後就是我們範例的起始點。 ```html <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw() { var canvas = document.getElementById("tutorial"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); } } </script> <style type="text/css"> canvas { border: 1px solid black; } </style> </head> <body onload="draw();"> <canvas id="tutorial" width="150" height="150"></canvas> </body> </html> ``` 一旦網頁載入完成後,程式碼會呼叫 draw()函數(這是利用 document 上的 load 事件完成),這類 draw()函數也可以透過`window.setTimeout()` (en-US), `window.setInterval()` (en-US)或其他事件處理函數來呼叫,只要呼叫的時間點是在網頁載入完後。 這是我們的範本實際看起來的樣子: 一個簡單的範例 ------- 首先,讓我們先來畫兩個相交的正方形,其中一個正方形有 alpha 透明值,之後我們會說明這是如何達成的。 ```html <html> <head> <script type="application/javascript"> function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect(10, 10, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect(30, 30, 55, 50); } } </script> </head> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` 本範例的結果如下: | Screenshot | Live sample | | --- | --- | | | | * « 前頁 * 次頁 »
繪製圖形 - Web APIs
繪製圖形 ==== * « 前頁 * 次頁 » 網格(Grid) ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes/canvas_default_grid.png)在開始繪圖前,我們必須先了解畫布 (canvas) 網格,或著是說座標空間。在前一頁教學中的 HTML 範本有一個寬 150 pixels (像素)、高 150 pixels 的畫布。如右圖,你在畫布預設網格上繪圖,網格上 1 單位相當於畫布上 1 pixel,網格的原點 (座標 (0, 0) ) 坐落於左上角,所有元素定位皆相對於此左上角原點,所以藍色方塊的位置為從左往右推 x pixels、從上往下推 y pixels (亦即座標 (x, y) )。現在我們先專注在預設設定上,之後我們會看到如何轉換原點位置、旋轉網格以及縮放網格。 畫矩形 --- 不同於SVG,`<canvas>`只支援一種原始圖形,矩形。所有的圖形都必須由一或多個繪圖路徑構成,而我們正好有一些繪圖路徑函數可以讓我們畫出複雜的圖形。 首先來看看矩形,共有三個矩形繪圖函數: `fillRect(x, y, width, height)` 畫出一個填滿的矩形。 `strokeRect(x, y, width, height)` 畫出一個矩形的邊框 `clearRect(x, y, width, height)` 清除指定矩形區域內的內容,使其變為全透明。 這三個函數都接受一樣的參數: x, y 代表從原點出發的座標位置,width, height 代表矩形的寬高。 ### 矩形範例 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } } ``` 本例結果如下: | Screenshot | Live sample | | --- | --- | | | | fillRect()函數畫出一個寬高都 100 pixels 的矩形,clearRect()函數清除中央 60 x 60 pixels 大的正方形區域,接著 strokeRect()在被清除區域內畫上一個 50 x 50 pixels 的矩形邊框。 之後我們會看到另外兩種代替 clearRect()的方法,還有如何改變圖形顏色與筆畫樣式。 不像之後會看到的路徑繪圖函數,這三個函數會立即在畫布上畫出矩形。 路徑繪製 ---- 使用路徑 (path) 來畫圖形需要多一點步驟,一開始先產生路徑,然後用繪圖指令畫出路徑,然後再結束路徑,一旦路徑產生後便可以用畫筆或填滿方式來渲染生成,這裡是一些可用函數: `beginPath()` (en-US) 產生一個新路徑,產生後再使用繪圖指令來設定路徑。 `closePath()` (en-US) 閉合路徑好讓新的繪圖指令來設定路徑。 路徑 API (en-US) 路徑 API,這些 API 便是繪圖指令 `stroke()` (en-US) 畫出圖形的邊框。 `fill()` (en-US) 填滿路徑內容區域來產生圖形。 第一步呼叫 beginPath() 產生一個路徑,表面下,路徑會被存在一個次路徑 (sub-path) 清單中,例如直線、曲線等,這些次路徑集合起來就形成一塊圖形。每一次呼叫這個方法,次路徑清單就會被重設,然後我們便能夠畫另一個新圖形。 **備註:** 當目前路徑為空(例如接著呼叫 beginPath()完後)或是在一個新畫布上,不論為何,第一個路徑繪圖指令總是 moveTo();因為每當重設路徑後,你幾乎都會需要設定繪圖起始點。 第二步是呼叫各式方法來實際設定繪圖路徑,稍後我們將會介紹這部分。 第三步,也是非必要的一步,就是呼叫 closePath()。這個方法會在現在所在點到起始點間畫一條直線以閉合圖形,如果圖形已經閉合或是只含一個點,這個方法不會有任何效果。 **備註:** 當呼叫 fill(),任何開放的圖形都會自動閉合,所以不需要再呼叫 closePath(),但是 stroke()並非如此。 ### 畫一個三角形 這是一個畫出三角形的程式碼範例。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(75, 50); ctx.lineTo(100, 75); ctx.lineTo(100, 25); ctx.fill(); } } ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | ### 移動畫筆 moveTo()是一個很有用的函數,moveTo()不會畫任何圖形,但卻是上述路徑清單的一部分,這大概有點像是把筆從紙上一點提起來,然後放到另一個點。 `moveTo(x, y)` (en-US) 移動畫筆到指定的(x, y)座標點 當初始化畫布或是呼叫 beginPath(),通常會想要使用 moveTo()來指定起始點,我們可以用 moveTo()畫不連結的路徑,看一下笑臉圖範例,圖中紅線即為使用到 moveTo()的位置。 你可以拿下面的程式碼,放進先前的 draw()函數,自己試試看效果。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI \* 2, true); // Outer circle ctx.moveTo(110, 75); ctx.arc(75, 75, 35, 0, Math.PI, false); // Mouth (clockwise) ctx.moveTo(65, 65); ctx.arc(60, 65, 5, 0, Math.PI \* 2, true); // Left eye ctx.moveTo(95, 65); ctx.arc(90, 65, 5, 0, Math.PI \* 2, true); // Right eye ctx.stroke(); } } ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | 移除 moveTo() 便可以看到線條連結起來。 **備註:** 有關 arc(),請參照下方弧形。 ### 線條 用 lineTo() 方法畫直線。 `lineTo(x, y)` (en-US) 從目前繪圖點畫一條直線到指定的(x, y)座標點。 本方法接受 x, y 參數作為線條結束點的座標位置,至於起始點則視前一個繪圖路徑,由前一個繪圖路徑的結束點作為起始點,當然,起始點也可以用 moveTo()方法來變更。 下面畫兩個三角形,一個填滿,一個空心。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // Filled triangle ctx.beginPath(); ctx.moveTo(25, 25); ctx.lineTo(105, 25); ctx.lineTo(25, 105); ctx.fill(); // Stroked triangle ctx.beginPath(); ctx.moveTo(125, 125); ctx.lineTo(125, 45); ctx.lineTo(45, 125); ctx.closePath(); ctx.stroke(); } } ``` 從呼叫 beginPath()起始一個新圖形路徑,然後用 moveTo()移到我們想要的起始點,然後再畫兩條線形成三角形的兩邊。 | Screenshot | Live sample | | --- | --- | | | | 我們可以看到填滿(fill)三角形和勾勒(stroke)三角形的區別;當填滿時,圖形會自動閉合,不過勾勒則不會,所以如果沒有呼叫 closePaht()的話,只會畫出兩條線而非三角形。 ### 弧形 用 arc()方法來畫弧形或圓形。雖然也可以用 arcTo(),但這個方法比較不可靠,所以這裡我們不討論 arcTo()。 `arc(x, y, radius, startAngle, endAngle, anticlockwise)` (en-US) 畫一個弧形 本方法接受五個參數: x, y 代表圓心座標點,radius 代表半徑,startAngle, endAngle 分別代表沿著弧形曲線上的起始點與結束點的弧度,弧度測量是相對於 x 軸,anticlockwise 為 true 代表逆時針作圖、false 代表順時針作圖。 **備註:** arc()方法用的是弧度(radians)而非角度(degrees),如果要在弧度與角度間換算,可以利用以下 javascript 程式碼: radians = (Math.PI/180) \* degrees. 以下例子比較複雜,它會畫出 12 個不同的弧形。 兩個 for 迴圈走一遍弧形圖列的列跟行,每一個弧形由呼叫 beginPath()開始新的繪圖路徑,為了清楚,我們在程式範例中用變數儲存參數,你不一定要這麼做。 x, y 座標點的部分應該相當淺顯,radius 和 startAngle 是定值,endAngle 從 180 度(半圓)開始,然後每一行增加 90 度,最後一行便會形成一個完整的圓。 第 1, 3 列的 anticlockwise 為 false,所以會順時針作圖,2, 4 列的 anticlockwise 為 true,所以會逆時針作圖。最後的 if 決定下半部是用填滿圖形,上半部是勾勒圖形。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="200"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 4; i++) { for (var j = 0; j < 3; j++) { ctx.beginPath(); var x = 25 + j \* 50; // x coordinate var y = 25 + i \* 50; // y coordinate var radius = 20; // Arc radius var startAngle = 0; // Starting point on circle var endAngle = Math.PI + (Math.PI \* j) / 2; // End point on circle var anticlockwise = i % 2 == 0 ? false : true; // clockwise or anticlockwise ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise); if (i > 1) { ctx.fill(); } else { ctx.stroke(); } } } } } ``` | Screenshot | Live sample | | --- | --- | | | | ### 貝茲曲線(Bezier curve)與二次曲線(quadratic curve) 二次與三次貝茲曲線(Bézier curves)是另一種可用來構成複雜有機圖形的路徑。 `quadraticCurveTo(cp1x, cp1y, x, y)` (en-US) 從目前起始點畫一條二次貝茲曲線到 x, y 指定的終點,控制點由 cp1x, cp1y 指定。 `bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)` (en-US) 從目前起始點畫一條三次貝茲曲線到 x, y 指定的終點,控制點由(cp1x, cp1y)和(cp2x, cp2y)指定。 ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes/canvas_curves.png)二次和三次的差別可以從右圖看出;貝茲曲線的起始和終點以藍點標示,其中二次貝茲曲線只有一個控制點(如紅點標示)而三次貝茲曲線有兩個控制點。 二次和三次貝茲曲線都用 x, y 參數定義終點座標,然後用 cp1x, xp1y 定義第一個控制點座標、cp2x, xp2y 定義第二個控制點座標。 用二次和三次貝茲曲線作圖相當具有挑戰性,因為不像使用 Adobe illustrator 的向量繪圖軟體,我們在繪圖時無法即時看到繪圖狀況,所以畫複雜的圖形十分困難。下面的範例我們畫了一些圖形,如果你有時間與耐心,可以畫出更複雜的圖形。 #### 二次貝茲曲線 本例用了數個二次貝茲曲線畫了一個會話框。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // Quadratric curves example ctx.beginPath(); ctx.moveTo(75, 25); ctx.quadraticCurveTo(25, 25, 25, 62.5); ctx.quadraticCurveTo(25, 100, 50, 100); ctx.quadraticCurveTo(50, 120, 30, 125); ctx.quadraticCurveTo(60, 120, 65, 100); ctx.quadraticCurveTo(125, 100, 125, 62.5); ctx.quadraticCurveTo(125, 25, 75, 25); ctx.stroke(); } } ``` | Screenshot | Live sample | | --- | --- | | | | #### 三次貝茲曲線 這個範例畫了一個愛心。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // Quadratric curves example ctx.beginPath(); ctx.moveTo(75, 40); ctx.bezierCurveTo(75, 37, 70, 25, 50, 25); ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5); ctx.bezierCurveTo(20, 80, 40, 102, 75, 120); ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5); ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25); ctx.bezierCurveTo(85, 25, 75, 37, 75, 40); ctx.fill(); } } ``` | Screenshot | Live sample | | --- | --- | | | | ### 矩形 除了在{畫矩形}段落中提到的三個方法,還有 rect()方法能夠在畫布上畫矩形;rect()方法會在目前路徑下加入一個矩形繪圖路徑。 `rect(x, y, width, height)` (en-US) 畫一個左上角位於(x, y)、寬 width、高 height 的矩形。 呼叫這個方法,moveTo()方法會以(0, 0)參數被自動呼叫,所以目前的下筆點跟者自動被設為預設座標。 ### 多樣組合 截至目前為止,我們都只用一種路徑函數在各個範例裡作圖,不過,其實繪圖時並沒有任何使用數量或種類上的路徑函數限制,所以最後我們來試著組合各樣路徑繪圖函數來畫一些十分有名的遊戲角色。 ``` <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> ``` ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); roundedRect(ctx, 12, 12, 150, 150, 15); roundedRect(ctx, 19, 19, 150, 150, 9); roundedRect(ctx, 53, 53, 49, 33, 10); roundedRect(ctx, 53, 119, 49, 16, 6); roundedRect(ctx, 135, 53, 49, 33, 10); roundedRect(ctx, 135, 119, 25, 49, 10); ctx.beginPath(); ctx.arc(37, 37, 13, Math.PI / 7, -Math.PI / 7, false); ctx.lineTo(31, 37); ctx.fill(); for (var i = 0; i < 8; i++) { ctx.fillRect(51 + i \* 16, 35, 4, 4); } for (i = 0; i < 6; i++) { ctx.fillRect(115, 51 + i \* 16, 4, 4); } for (i = 0; i < 8; i++) { ctx.fillRect(51 + i \* 16, 99, 4, 4); } ctx.beginPath(); ctx.moveTo(83, 116); ctx.lineTo(83, 102); ctx.bezierCurveTo(83, 94, 89, 88, 97, 88); ctx.bezierCurveTo(105, 88, 111, 94, 111, 102); ctx.lineTo(111, 116); ctx.lineTo(106.333, 111.333); ctx.lineTo(101.666, 116); ctx.lineTo(97, 111.333); ctx.lineTo(92.333, 116); ctx.lineTo(87.666, 111.333); ctx.lineTo(83, 116); ctx.fill(); ctx.fillStyle = "white"; ctx.beginPath(); ctx.moveTo(91, 96); ctx.bezierCurveTo(88, 96, 87, 99, 87, 101); ctx.bezierCurveTo(87, 103, 88, 106, 91, 106); ctx.bezierCurveTo(94, 106, 95, 103, 95, 101); ctx.bezierCurveTo(95, 99, 94, 96, 91, 96); ctx.moveTo(103, 96); ctx.bezierCurveTo(100, 96, 99, 99, 99, 101); ctx.bezierCurveTo(99, 103, 100, 106, 103, 106); ctx.bezierCurveTo(106, 106, 107, 103, 107, 101); ctx.bezierCurveTo(107, 99, 106, 96, 103, 96); ctx.fill(); ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(101, 102, 2, 0, Math.PI \* 2, true); ctx.fill(); ctx.beginPath(); ctx.arc(89, 102, 2, 0, Math.PI \* 2, true); ctx.fill(); } } // A utility function to draw a rectangle with rounded corners. function roundedRect(ctx, x, y, width, height, radius) { ctx.beginPath(); ctx.moveTo(x, y + radius); ctx.lineTo(x, y + height - radius); ctx.quadraticCurveTo(x, y + height, x + radius, y + height); ctx.lineTo(x + width - radius, y + height); ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius); ctx.lineTo(x + width, y + radius); ctx.quadraticCurveTo(x + width, y, x + width - radius, y); ctx.lineTo(x + radius, y); ctx.quadraticCurveTo(x, y, x, y + radius); ctx.stroke(); } ``` 結果如下: 畫出這樣的圖其實沒有想像中的困難,所以我們就不再描述細節了,其中比較需要注意的是,我們在繪圖環境上用了 fillStyle 屬性以及一個自定義的效用函數(roundedRect()),利用效用函數來執行時常重複的繪圖工作可以幫忙減少程式碼數量與複雜度。 稍後我們會更進一步介紹 fillStyle 屬性,這個範例我們所做是的透過 fillStyle 屬性來改變路徑填滿色為白色,然後再改回預設黑色,來變換填滿顏色,。 * « 前頁 * 次頁 » Path2D objects -------------- 如同前面的範例,canvas 上常常會畫上一連串的繪圖路徑,為了簡化程式碼還有改善效能,我們可以利用 `Path2D` (en-US) 物件 (目前在較先進的瀏覽器上已經有提供了)。Path2D 讓我們可以快取和記錄繪圖指令,方便快速重複地繪圖,底下我就來看看如何使用 Path2D : `Path2D()` (en-US) Path2D 的建構子,可接受的參數有無參數、另一個 Path2D 物件、 字元表式的 SVG path: ```js new Path2D(); // 不傳入參數會回傳一個空的 Path2D 物件 new Path2D(path); // 複製傳入的 Path2D 物件,然後以之建立 Path2D 物件 new Path2D(d); // 以傳入的 SVG 路徑建立 Path2D 物件 ``` 所有已知的 路徑 API (en-US),如 rect, arc 等等,都可以在 Path2D 上找到。 Path2D 物件還可以加入其他 Path2D 物件,這讓我們可以很方便的組合多個物件使用。 `Path2D.addPath(path [, transform])` (en-US) addPath 增加一個 Path2D 物件,其中的非必要參數是變形矩陣。 ### Path2D example 這個例子用 Path2D 物件將矩形和圓形的繪圖路徑存起來,以供之後使用。而配合新的 Path2D API,有一些繪圖方法更接受傳入 Path2D 作為繪圖路徑使用,例如下方本例所用到的 stroke 和 fill。 ```js function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var rectangle = new Path2D(); rectangle.rect(10, 10, 50, 50); var circle = new Path2D(); circle.moveTo(125, 35); circle.arc(100, 35, 25, 0, 2 \* Math.PI); ctx.stroke(rectangle); ctx.fill(circle); } } ``` | Screenshot | Live sample | | --- | --- | | | | ### 使用向量路徑 (SVG paths) 另一個強而有力的特色是在 SVG 和 Canvas 中我們都可以使用 SVG path。 下面的路徑會移到座標點 (10, 10) (M10, 10),然後水平右移 80 點 (h 80),垂至下移 80 點 (v 80) 水平左移 80 點 (h -80) 最後回到起始點 (z),請到`Path2D` 建構子頁面 (en-US)看繪圖範例結果。 ```js var p = new Path2D("M10 10 h 80 v 80 h -80 Z"); ``` * « 前頁 * 次頁 »
Advanced animations - Web APIs
Advanced animations =================== * « 前頁 * 次頁 » 在上一章節,我們做了一些基礎動畫且知道它的移動方式。在這部分我們更仔細的介紹它的動畫效果且並增加一些特效,使它看起來更高級。 畫一顆球 ---- 在這次的動畫練習中使用球來練習。照著下面的步驟完成 canvas 設定。 ```html <canvas id="canvas" width="600" height="300"></canvas> ``` 照常理,先在 canvas 上需要先畫一顆球。創造一個 `ball` object,它包含的屬性和`draw()`的方法,使 canvas 可以在上面繪圖。 ```js var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var ball = { x: 100, y: 100, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; ball.draw(); ``` 這裡沒什麼特別的,透過`arc()` (en-US)的方法,球事實上只是畫下簡單的圓。 添加速度 ---- 現在有了一顆球,準備添加基礎的動畫像我們從上章節學到的課程。再次使用`window.requestAnimationFrame()`控制動畫。添加移動的向量速度使球移動到向量點。對於每個幀(frame),我們使用clear (en-US)來清除 canvas 舊的移動幀(frame)。 ```js var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; raf = window.requestAnimationFrame(draw); } canvas.addEventListener("mouseover", function (e) { raf = window.requestAnimationFrame(draw); }); canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); }); ball.draw(); ``` 邊界 -- 沒有任何邊界碰撞下,球很快就會跑出 canvas。這時需要確認球的 `x` and `y` 是否超出 canvas 尺寸,若超出則將球的向量顛倒。所以,我們添加了確認條件在`draw`方法: ```js if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } ``` ### 第一個示範 讓我們看看,看似很遠的行徑它如何行徑。移動你的滑鼠在 canvas,使動畫開始。 ``` <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> ``` ``` var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestAnimationFrame(draw); } canvas.addEventListener("mouseover", function (e) { raf = window.requestAnimationFrame(draw); }); canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); }); ball.draw(); ``` 加速性能 ---- 為了使移動看起來更真實,你可以照著範例改變速度: ```js ball.vy \*= 0.99; ball.vy += 0.25; ``` 這個使每個幀(frame)的垂直向量減少,所以球將只會在地板彈跳直到結束。 ``` <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> ``` ``` var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; ball.vy \*= 0.99; ball.vy += 0.25; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestAnimationFrame(draw); } canvas.addEventListener("mouseover", function (e) { raf = window.requestAnimationFrame(draw); }); canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); }); ball.draw(); ``` 追蹤效果 ---- 直到現在我們已經使用`clearRect` (en-US)方法清除之前的幀(frames)。如果使用重置半透明`fillRect` (en-US)這個方法,可以更淺顯的看出創造追蹤效果。 ```js ctx.fillStyle = "rgba(255, 255, 255, 0.3)"; ctx.fillRect(0, 0, canvas.width, canvas.height); ``` ``` <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> ``` ``` var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; function draw() { ctx.fillStyle = "rgba(255, 255, 255, 0.3)"; ctx.fillRect(0, 0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; ball.vy \*= 0.99; ball.vy += 0.25; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestAnimationFrame(draw); } canvas.addEventListener("mouseover", function (e) { raf = window.requestAnimationFrame(draw); }); canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); }); ball.draw(); ``` 增加滑鼠控制 ------ 為了能控制球使它跟著滑鼠移動,在這個範例使用`mousemove` (en-US) 效果。當 `click` (en-US) 事件觸發了這顆球,它又會開始彈跳。 ``` <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> ``` ```js var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var raf; var running = false; var ball = { x: 100, y: 100, vx: 5, vy: 1, radius: 25, color: "blue", draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI \* 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); }, }; function clear() { ctx.fillStyle = "rgba(255, 255, 255, 0.3)"; ctx.fillRect(0, 0, canvas.width, canvas.height); } function draw() { clear(); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestAnimationFrame(draw); } canvas.addEventListener("mousemove", function (e) { if (!running) { clear(); ball.x = e.clientX; ball.y = e.clientY; ball.draw(); } }); canvas.addEventListener("click", function (e) { if (!running) { raf = window.requestAnimationFrame(draw); running = true; } }); canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); running = false; }); ball.draw(); ``` 用你的滑鼠移動這顆球且點擊鬆放它。 突破性(遊戲) ------- 這個小章節只有解釋一些創造高級動畫的技巧。這裡還有更多!如何增加槳,磚塊,到這個 到 Breakout game demo 去看,有我們更多遊戲研發的文章! 延伸閱讀 ---- * `window.requestAnimationFrame()` * Efficient animation for web games (en-US) * « 前頁 * 次頁 »
Pixel manipulation with canvas - Web APIs
Pixel manipulation with canvas ============================== * « 前頁 * 次頁 » 直到目前為止,我們還沒真正了解 pixels 在 canvas 上的運用。使用`ImageData`物件,可直接對 pixel 裡的陣列資料**讀(read)**和**寫(write)**。在接下的內容中,也可了解到如何使影像平滑化(反鋸齒)及如何將影像保存在 canvas 之中。 `ImageData`物件 ------------- `ImageData` (en-US) 物件代表 canvas 區中最基礎的像素。 包含它只可讀的屬性: `width` 影像中的寬度,以 pixels 為單位 `height` 影像中的高度,以 pixels 為單位 `data` `Uint8ClampedArray` (en-US) 代表一維陣列包含 RGBA 格式。整數值介於 0 到 255 之間(包含 255)。 `data` 屬性返回一個`Uint8ClampedArray` (en-US),它可被當作為 pixel 的初始資料。每個 pixel 用 4 個 1byte 值做代表分別為**紅**,**綠**,**藍**,**透明值**(也就是**RGBA**格式)。每個顏色組成皆是介於整數值介於 0 到 255 之間。而每個組成在一個陣列中被分配為一個連續的索引。從左上角 pixel 的紅色組成中的陣列由**索引 0** 為始。Pixels 執行順序為從左到右,再由上到下,直到整個陣列。 `Uint8ClampedArray` (en-US) 包含`height` × `width`× 4 bytes 的資料,同索引值從 0 到 (`height`×`width`×4)-1 例如,讀取影像的藍色組成的值。從 pixel 的第 200 欄、第 50 行,你可以照著下面的步驟: ```js blueComponent = imageData.data[50 \* (imageData.width \* 4) + 200 \* 4 + 2]; ``` 使用`Uint8ClampedArray.length`屬性來讀取影像 pixel 的陣列大小 ```js var numBytes = imageData.data.length; ``` 創造一個 `ImageData`物件 ------------------ 可以使用`createImageData()` (en-US)方法創造一個全新空白的`ImageData` 物件。 這裡有兩種`createImageData()`的方法: ```js var myImageData = ctx.createImageData(width, height); ``` 這個方法是有規定大小尺寸.所有 pixels 預設是透明的黑色。 下面的方法一樣是由`anotherImageData`參考尺寸大小,由`ImageData` 物件創造一個與新的一樣的大小。這些新的物件的 pixel 皆預設為透明的黑色。 ```js var myImageData = ctx.createImageData(anotherImageData); ``` 得到 pixel 資料的內容 -------------- 可以使用`getImageData()`這個方法,去取得 canvas 內容中`ImageData` 物件的資料含 pixel 數據(data) ```js var myImageData = ctx.getImageData(left, top, width, height); ``` 這個方法會返回`ImageData`物件,它代表著在這 canvas 區域之中 pixel 的數據(data) 。從各角落的點代表著 (`left`,`top`), (`left+width`, `top`), (`left`, `top+height`), and (`left+width`, `top+height`)。這些作標被設定為 canvas 的空間座標單位。 **備註:** 在`ImageData` 物件中,任何超出 canvas 外的 pixels 皆會返回透明的黑色的形式。 這個方法也被展示在使用 canvas 操作影像 (en-US)之中。 ### 調色盤 這個範例使用getImageData() (en-US) 方法去顯示在鼠標下的顏色。 首先,需要一個正確的滑鼠點`layerX` 和 `layerY`。在從getImageData() (en-US) 提供 pixel 陣列中(array)該點的 pixel 數據(data) 。最後,使用陣列數據(array data)在`<div>`中設置背景色和文字去顯示該色。 ``` <canvas id="canvas" width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div> ``` ```js var img = new Image(); img.src = "rhino.jpg"; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); img.onload = function () { ctx.drawImage(img, 0, 0); img.style.display = "none"; }; var color = document.getElementById("color"); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; var rgba = "rgba(" + data[0] + ", " + data[1] + ", " + data[2] + ", " + data[3] / 255 + ")"; color.style.background = rgba; color.textContent = rgba; } canvas.addEventListener("mousemove", pick); ``` 在內容中寫入 pixel 資料 --------------- 可以使用putImageData() (en-US) 方法將自訂 pixel 數據(data) 放入內容中: ```js ctx.putImageData(myImageData, dx, dy); ``` `dx` 和 `dy`參數表示填入你所希望的座標,將它代入內容中左上角的 pixel 數據(data)。 For example, to paint the entire image represented by `myImageData` to the top left corner of the context, you can simply do the following: ```js ctx.putImageData(myImageData, 0, 0); ``` ### 灰階和負片效果 In this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putImageData() (en-US). The invert function simply subtracts each color from the max value 255. The grayscale function simply uses the average of red, green and blue. You can also use a weighted average, given by the formula `x = 0.299r + 0.587g + 0.114b`, for example. See Grayscale on Wikipedia for more information. ``` <canvas id="canvas" width="300" height="227"></canvas> <div> <input id="grayscalebtn" value="Grayscale" type="button" /> <input id="invertbtn" value="Invert" type="button" /> </div> ``` ```js var img = new Image(); img.src = "rhino.jpg"; img.onload = function () { draw(this); }; function draw(img) { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); img.style.display = "none"; var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; var invert = function () { for (var i = 0; i < data.length; i += 4) { data[i] = 255 - data[i]; // red data[i + 1] = 255 - data[i + 1]; // green data[i + 2] = 255 - data[i + 2]; // blue } ctx.putImageData(imageData, 0, 0); }; var grayscale = function () { for (var i = 0; i < data.length; i += 4) { var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; data[i] = avg; // red data[i + 1] = avg; // green data[i + 2] = avg; // blue } ctx.putImageData(imageData, 0, 0); }; var invertbtn = document.getElementById("invertbtn"); invertbtn.addEventListener("click", invert); var grayscalebtn = document.getElementById("grayscalebtn"); grayscalebtn.addEventListener("click", grayscale); } ``` 放大和平滑化(反鋸齒) ----------- With the help of the `drawImage()` (en-US) method, a second canvas and the `imageSmoothingEnabled` (en-US) property, we are able to zoom into our picture and see the details. We get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. Then we copy that one over to another canvas and resize the image to the size we want it to. In the zoom canvas we resize a 10×10 pixel crop of the original canvas to 200×200. ```js zoomctx.drawImage( canvas, Math.abs(x - 5), Math.abs(y - 5), 10, 10, 0, 0, 200, 200, ); ``` Because anti-aliasing is enabled by default, we might want to disable the smoothing to see clear pixels. You can toggle the checkbox to see the effect of the `imageSmoothingEnabled` property (which needs prefixes for different browsers). ### Zoom example ``` <canvas id="canvas" width="300" height="227"></canvas> <canvas id="zoom" width="300" height="227"></canvas> <div> <label for="smoothbtn"> <input type="checkbox" name="smoothbtn" checked="checked" id="smoothbtn" /> Enable image smoothing </label> </div> ``` ```js var img = new Image(); img.src = "rhino.jpg"; img.onload = function () { draw(this); }; function draw(img) { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); img.style.display = "none"; var zoomctx = document.getElementById("zoom").getContext("2d"); var smoothbtn = document.getElementById("smoothbtn"); var toggleSmoothing = function (event) { zoomctx.imageSmoothingEnabled = this.checked; zoomctx.mozImageSmoothingEnabled = this.checked; zoomctx.webkitImageSmoothingEnabled = this.checked; zoomctx.msImageSmoothingEnabled = this.checked; }; smoothbtn.addEventListener("change", toggleSmoothing); var zoom = function (event) { var x = event.layerX; var y = event.layerY; zoomctx.drawImage( canvas, Math.abs(x - 5), Math.abs(y - 5), 10, 10, 0, 0, 200, 200, ); }; canvas.addEventListener("mousemove", zoom); } ``` 儲存圖片 ---- The `HTMLCanvasElement` (en-US) provides a `toDataURL()` method, which is useful when saving images. It returns a data URI (en-US) containing a representation of the image in the format specified by the `type` parameter (defaults to PNG). The returned image is in a resolution of 96 dpi. `canvas.toDataURL('image/png')` Default setting. Creates a PNG image. `canvas.toDataURL('image/jpeg', quality)` Creates a JPG image. Optionally, you can provide a quality in the range from 0 to 1, with one being the best quality and with 0 almost not recognizable but small in file size. Once you have generated a data URI from you canvas, you are able to use it as the source of any `<image>` (en-US) or put it into a hyper link with a download attribute (en-US) to save it to disc, for example. You can also create a `Blob` from the canvas. `canvas.toBlob(callback, type, encoderOptions)` (en-US) Creates a `Blob` object representing the image contained in the canvas. 延伸閱讀 ---- * `ImageData` (en-US) * Manipulating video using canvas (en-US) * Canvas, images and pixels – by Christian Heilmann * « 前頁 * 次頁 »
套用樣式與顏色 - Web APIs
套用樣式與顏色 ======= * « 前頁 * 次頁 » 在繪畫圖形章節中,我們只用了預設的線條與填滿樣式,而在本章,我們將進一步看看所有可用的樣式選項,畫出更吸引人的圖。 顏色 -- U 截至目前為止我們只有看到繪圖環境的方法(methods),如果我們想要設定圖形的顏色,我們有兩個屬性能用: `fillStyle`與`storkeStyle.` `fillStyle = color` 設定填滿圖形時用的顏色. `strokeStyle = color` 設定勾勒圖形時用的顏色. 其中`color`可以是 CSS`<color>` (en-US)表示字串、漸層色物件(gradient color)或是模式物件(pattern object),現在先看一下 CSS{<color>}表示字串,稍後再看另外兩個項目. 預設上勾勒和填滿色是黑色(CSS 顏色值為#000000). **備註:** 一旦改變了 strokeStyle 的顏色值,那麼之後圖形勾勒顏色都會變成新顏色,同樣狀況一樣適用於 fillStyle. 合格的顏色值請參照 CSS3`<color>` (en-US)規範,下面範例所標示的顏色都指向同一個顏色. ```js // these all set the fillStyle to 'orange' ctx.fillStyle = "orange"; ctx.fillStyle = "#FFA500"; ctx.fillStyle = "rgb(255,165,0)"; ctx.fillStyle = "rgba(255,165,0,1)"; ``` **備註:** 目前 Gecko 引擎並不支援 CSS3 全部的顏色值,例如 hsl(100%,25%,0)和 rgb(0,100%,0)就不被支援. ### `fillStyle` 範例 這裡我們利用兩個 for 迴圈來畫出一個矩形陣列,而且陣列中每一個矩形的顏色都不相同。下面程式碼透過改變 i 和 j 兩個變數來分別變換 RGB 中的紅色值和綠色值,然後為每一個矩形產生自己專屬的顏色值。透過改變 RGB 的各顏色值,我們可以產生各式各樣的調色盤,像是逐步調整顏色值,你也可以做出像 Photoshop 內建一樣的調色盤。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = "rgb(" + Math.floor(255 - 42.5 \* i) + "," + Math.floor(255 - 42.5 \* j) + ",0)"; ctx.fillRect(j \* 25, i \* 25, 25, 25); } } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | ### `strokeStyle` 範例 本例和前例相當類似,不同的是我們改用 arc()方法畫圓形而不是矩形、改設定 strokeStyle 變換圖形輪廓顏色。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokeStyle = "rgb(0," + Math.floor(255 - 42.5 \* i) + "," + Math.floor(255 - 42.5 \* j) + ")"; ctx.beginPath(); ctx.arc(12.5 + j \* 25, 12.5 + i \* 25, 10, 0, Math.PI \* 2, true); ctx.stroke(); } } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 結果如下: | Screenshot | Live sample | | --- | --- | | | | 透明度 --- 透過設定 globalAlpha 屬性或是以半透明顏色值設定 strokeStyle 與 fillStyle 屬性,除了畫不透明的圖形,我們還可以畫半透明的圖形。 `globalAlpha = transparencyValue` 允許值介於 0.0(全透明)到 1.0(不透明)。一旦設定後,之後畫布上畫的所有圖形的不透明度都會套用此設定值。預設值為 1.0。 當我們想畫一系列相同不透明度的圖,設定 globalAlpha 值是一個方便的作法。 由 CSS3 顏色值能夠指定不透明度,我們也可以如下面一般,設定 strokeStyle 以及 fillStyle 來變更不透明度。 ```js // Assigning transparent colors to stroke and fill style ctx.strokeStyle = "rgba(255,0,0,0.5)"; ctx.fillStyle = "rgba(255,0,0,0.5)"; ``` rgba()函數比 rgb()函數多出一個不透明度參數,允許值介於 0.0(全透明)到 1.0(不透明). ### `globalAlpha` 範例 下面我們將在四個方格色塊背景上畫一系列半透明圓形。對於所有圓形,我們藉由設置 globalAlpha 屬性值為 0.2 使得圓形變成半透明,然後 for 迴圈裡我們逐一增加圓形繪圖半徑,最終結果看起來便像是輻射狀漸層圖案,而且圓形相互疊加在彼此之上後,又加深了重疊區域的不透明度,只要我們不斷增加圓形數量,最後圖片中央將被完全遮蓋,看不到背後的背景。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // draw background ctx.fillStyle = "#FD0"; ctx.fillRect(0, 0, 75, 75); ctx.fillStyle = "#6C0"; ctx.fillRect(75, 0, 75, 75); ctx.fillStyle = "#09F"; ctx.fillRect(0, 75, 75, 75); ctx.fillStyle = "#F30"; ctx.fillRect(75, 75, 150, 150); ctx.fillStyle = "#FFF"; // set transparency value ctx.globalAlpha = 0.2; // Draw semi transparent circles for (i = 0; i < 7; i++) { ctx.beginPath(); ctx.arc(75, 75, 10 + 10 \* i, 0, Math.PI \* 2, true); ctx.fill(); } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | ### `rgba()` 使用範例 這個範例類似於上面的範例,但不同的是我們改畫半透明的矩形。rgba()在使用上會多一點彈性,因為我們可以分別設置勾勒和填滿圖形的不透明度。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // Draw background ctx.fillStyle = "rgb(255,221,0)"; ctx.fillRect(0, 0, 150, 37.5); ctx.fillStyle = "rgb(102,204,0)"; ctx.fillRect(0, 37.5, 150, 37.5); ctx.fillStyle = "rgb(0,153,255)"; ctx.fillRect(0, 75, 150, 37.5); ctx.fillStyle = "rgb(255,51,0)"; ctx.fillRect(0, 112.5, 150, 37.5); // Draw semi transparent rectangles for (var i = 0; i < 10; i++) { ctx.fillStyle = "rgba(255,255,255," + (i + 1) / 10 + ")"; for (var j = 0; j < 4; j++) { ctx.fillRect(5 + i \* 14, 5 + j \* 37.5, 14, 27.5); } } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | 線條樣式 ---- 有數種屬性可以讓我們設定線條樣式. `lineWidth = value` 設定線條寬度。 `lineCap = type` 設定線條結尾的樣式。 `lineJoin = type` 設定線條和線條間接合處的樣式。 `miterLimit = value` 限制當兩條線相交時交接處最大長度;所謂交接處長度(miter length)是指線條交接處內角頂點到外角頂點的長度。 底下我們將一一示範這些屬性的用途。 ### `lineWidth` 範例 此屬性決定線條寬度,必須為正數,預設值為 1.0 單位。 線條寬度的起算點是從繪圖路徑中央開始往兩旁各延伸一半設定寬度,由於畫布座標不直接對應到像素(pixel),所以要比較小心設定好取得清晰的直線。 由下方例子可以明顯看到,畫布上有 10 條直線,由左至右,從最小的 1.0 單位寬開始逐漸加寬,請注意奇數寬度直線會因為繪圖路徑位置關係而比較模糊。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); for (var i = 0; i < 10; i++) { ctx.lineWidth = 1 + i; ctx.beginPath(); ctx.moveTo(5 + i \* 14, 5); ctx.lineTo(5 + i \* 14, 140); ctx.stroke(); } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | 為了畫出清晰的直線,我們需要了解繪圖路徑是如何產生;如下方圖示,網格代表畫布座標軸,網格所框出的方格則代表螢幕上的像素,第一張圖片填滿了座標(2,1)到(5,5)的紅色區域,而這個紅色區域的邊際正好符合像素間的邊際,所以會產生出清晰的影像。 ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors/canvas-grid.png) 第二張圖片中,有一條寬 1.0 單位的直線從座標(3,1)到(3,5)被畫在畫布上,不過由於線條寬度的起算點是從繪圖路徑中央開始往兩旁各延伸一半設定寬度,所以當勾勒線條時,繪圖路徑兩旁的像素格只有一半會被填滿暗藍色,至於另外一半則會經由計算填入近似色(淡藍色),結果就是整格像素並非全部填入相同的暗藍色,進而產生出邊緣較為模糊的線條,上面程式碼範例中的奇數寬度直線就是因此而產生不清晰的線條。 為了避免劃出邊緣模糊直線,我們必須精準設定繪圖路徑位置,就本範例而言,如果我們的直線繪圖路徑是從座標(3.5, 1)到(3.5, 5)的話(如第三張圖),那麼 1.0 單位寬的直線將剛好填滿像素格,所以我們將可以畫出清晰的直線。 **備註:** 請注意本範例的 Y 軸座標都是整數點,若非如此,一樣會導致線條端點的像素格無法剛好被填滿的現象,而且同時最後產生的結果也會被 lineCap 給影響;倘若 lineCap 值為預設 butt 時,我們會需要為奇數寬度直線計算一下非整數的座標點,倘若 lineCap 樣式為 square,那麼線段端點的像素格將自動被完整填滿。還有一點需要注意,只要繪圖路徑被 closePath()函數閉合起來,這樣便沒有了線條端點,所有的線條端點都會依據 lineJoin 樣式全部前後互相連接起來,這會自動延伸端點邊緣到線段接合處,如果此時接合端點是水平或垂直的話,位於中央的像素格將會被完整填滿。後面的說明會介紹 lineCap 和 lineJoin 樣式。 至於本例中偶數寬度的直線,為了避免模糊,繪圖路徑最好是落在整數座標點上。 雖然處裡 2D 繪圖縮放有些麻煩,但只要仔細計算像素格和繪圖路徑位置,縱使進行圖像縮放或變形,圖像輸出還是可以保持正確。一條寬 1.0 單位的直線,只要位置計算正確,放大兩倍後會變成一條 2 個像素寬的清晰直線,而且還是會保持正確位置。 ### `lineCap` 範例 這個屬性決定線條端點的樣式,總共有三種樣式可選: ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors/canvas_linecap.png) `butt` 線條端點樣式為方形 `round` 線條端點樣式為圓形 `square` 增加寬同線條寬度、高線條寬度一半的的方塊於線條端點 下面程式碼會畫出三條線,每條線的 lineCap 值皆不同。然後為了看清差異點,我們加上了兩條淡藍色的輔助線,線條的繪圖起始點和終點都剛好落在輔助線上。 最左邊的線條其 lineCap 為 butt,不難看出它完全介於輔助線之間;第二條線其 lineCap 為 round,端點樣式為半徑等於線條寬度一半的半圓;最右邊的線條其 lineCap 為 square,端點樣式為寬同線條寬度、高線條寬度一半的的方塊。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); var lineCap = ["butt", "round", "square"]; // Draw guides ctx.strokeStyle = "#09f"; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(140, 10); ctx.moveTo(10, 140); ctx.lineTo(140, 140); ctx.stroke(); // Draw lines ctx.strokeStyle = "black"; for (var i = 0; i < lineCap.length; i++) { ctx.lineWidth = 15; ctx.lineCap = lineCap[i]; ctx.beginPath(); ctx.moveTo(25 + i \* 50, 10); ctx.lineTo(25 + i \* 50, 140); ctx.stroke(); } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | ### `lineJoin` 範例 lineJoin 屬性決定兩個連接區端(如線條、弧形或曲線)如何連接(對於長度為零,亦即終點和控制點為同一點的圖形無效)。 lineJoin 屬性共有三個屬性值如下,其中 miter 為預設值,請注意一點若是兩個連接區段的繪圖方向一致,那代表不會有連接處,所以測定是無效的。 ![](/zh-TW/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors/canvas_linejoin.png) `round` 代表圓弧型連接樣式。 `bevel` 代表斜面型連接樣式。在連接區段的共同終點處填滿一個三角形區域,將原本的外接角處形成一個切面。 `miter` 代表斜交型連接樣式。向外延伸連結區段外緣直到相交於一點,然後形成菱形區域,而 miterLimit 屬性會影響 miter 屬性。 下方程式碼和圖形輸出展示了 lineJoin 在不同屬性值下呈現的不同結果 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); var lineJoin = ["round", "bevel", "miter"]; ctx.lineWidth = 10; for (var i = 0; i < lineJoin.length; i++) { ctx.lineJoin = lineJoin[i]; ctx.beginPath(); ctx.moveTo(-5, 5 + i \* 40); ctx.lineTo(35, 45 + i \* 40); ctx.lineTo(75, 5 + i \* 40); ctx.lineTo(115, 45 + i \* 40); ctx.lineTo(155, 5 + i \* 40); ctx.stroke(); } } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | ### `miterLimit` 屬性 前面範例顯示出,當 lineJoin 值為 miter 時,兩條線的外緣會延伸相交,所以,當這兩條相交線的相交角度越小的話,他們的延伸交會點就會越遠離內緣連接點,而且隨著角度變小,距離呈指數型增長。 miterLimit 會限制延伸交會點最遠可以離內緣連接點到多遠,當延伸交會點的落點超出這個範圍,那麼便以斜面(bevel)作為交接樣式。請注意,最大 miter 長度為線寬乘於 miterLimit 值,所以 miterLimit 可以獨立於目前顯示縮放尺寸或其他變形設定。 miterLimit 預設值為 10.0。 更精確來說,miter 限制是指延伸長度(在 HTML 畫布上,這個長度是外緣相交角到連接區段的共同繪圖路經終點)相對於一半線寬的最大允許比率;也等同於,外緣距內緣相交點之距離相對於線寬的的最大允許比率;相當於,連接區最小內緣角的一半角度的餘割(cosecant)值, 小於此值則便以斜面(bevel)作為交接樣式: * `miterLimit` = **max** `miterLength` / `lineWidth` = 1 / **sin** ( **min** *θ* / 2 ) * 10.0 的預設 miterLimit 值會移除任何角度小於 11 度的相接線段的 miter 交接。 * miter 限制值如果等於根號 2(約 1.4142136)會移除銳角的 miter 交接,只有直角或鈍角的不會被移除。 * miter 限制值如果等於 1.0 會移除所有的 miter 交接。 * 小於 1.0 不是合法的限制值。 下面是一個範例,其中藍線標示出各個線條繪圖路徑的起始點與終點。 倘若設定範例程式碼中的 miterLimit 低於 4.2,所有的 miter 交接都會被移除,取而代之的是出現在藍線附近的 bevel 交接;倘若設定 miterLimit 大於 10,那麼大部分的 miter 交接都會出現,而且你會發現,由左到右,miter 長度逐漸縮短,這是由於線條相交角度逐漸加大之故;倘若設定中間值,那麼左邊會出現 bevel 交接,右邊會出現 miter 交接。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // Clear canvas ctx.clearRect(0, 0, 150, 150); // Draw guides ctx.strokeStyle = "#09f"; ctx.lineWidth = 2; ctx.strokeRect(-5, 50, 160, 50); // Set line styles ctx.strokeStyle = "#000"; ctx.lineWidth = 10; // check input if (document.getElementById("miterLimit").value.match(/\d+(\.\d+)?/)) { ctx.miterLimit = parseFloat(document.getElementById("miterLimit").value); } else { alert("Value must be a positive number"); } // Draw lines ctx.beginPath(); ctx.moveTo(0, 100); for (i = 0; i < 24; i++) { var dy = i % 2 == 0 ? 25 : -25; ctx.lineTo(Math.pow(i, 1.5) \* 2, 75 + dy); } ctx.stroke(); return false; } ``` ``` <table> <tr> <td><canvas id="canvas" width="150" height="150"></canvas></td> <td> Change the <code>miterLimit</code> by entering a new value below and clicking the redraw button.<br /><br /> <form onsubmit="return draw();"> <label>Miter limit</label> <input type="text" size="3" id="miterLimit" /> <input type="submit" value="Redraw" /> </form> </td> </tr> </table> ``` ``` document.getElementById("miterLimit").value = document .getElementById("canvas") .getContext("2d").miterLimit; draw(); ``` | Screenshot | Live sample | | --- | --- | | | | 漸層 -- 如同其他繪圖軟體可以畫出線性和放射狀的漸層圖案,透過設定 fillStyle 和 strokeStyle 屬性為 canvasGradient 漸層物件,我們也可以在 canvas 上做到一樣的效果。要創造漸層物件,可以使用下面的方法: `createLinearGradient(x1, y1, x2, y2)` 產生一個線性漸層物件,其漸層起始點為(x1, y1)、終點為(x2, y2)。 `createRadialGradient(x1, y1, r1, x2, y2, r2)` 產生一個放射狀漸層物件,第一個圓之圓心落在(x1, y1)、半徑為 r1,第一個圓之圓心落在(x2, y2)、半徑為 r2。 例如: ```js var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100); ``` 一旦產生了 canvasGradient 漸層物件,我們用 addColorStop()方法可以添加顏色上去。 `gradient.addColorStop(position, color)` 於 gradient 漸層物件建立一個顏色點,其中 color 是 CSS`<color>` (en-US)的字串表示,而 position 介於 0.0 到 1.0 之間,定義了該顏色在漸層中的相對位置。呼叫這個方法會指定當進行到設定的位置時,漸層需要完全轉變成設定的顏色。 我們可以按照需要設定無數個顏色點,下面是一個簡單的由白到黑的簡單漸層範例程式碼。 ```js var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); lineargradient.addColorStop(0, "white"); lineargradient.addColorStop(1, "black"); ``` ### `createLinearGradient` 範例 本範例中,我們將建立兩種漸層,如範例所示,strokeStyle 和 fillSyle 屬性都可以接受 canvasGradient 物件作為屬性值。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // Create gradients var lingrad = ctx.createLinearGradient(0, 0, 0, 150); lingrad.addColorStop(0, "#00ABEB"); lingrad.addColorStop(0.5, "#fff"); lingrad.addColorStop(0.5, "#26C000"); lingrad.addColorStop(1, "#fff"); var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); lingrad2.addColorStop(0.5, "#000"); lingrad2.addColorStop(1, "rgba(0,0,0,0)"); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes ctx.fillRect(10, 10, 130, 130); ctx.strokeRect(50, 50, 50, 50); } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 第一個漸層為背景漸層,範例中我們在一個位置上指定了兩種顏色(白色到綠色),這樣做會產生非常突然的顏色轉換,一般來說,不管如何設定顏色點順序都沒關係,然而就這個例子而言,這種作法太過強烈了,但是如果這是你想要的顏色漸層順序,那其實也是可以。 第二個漸層起始位置(position 0.0)的顏色並沒有被指定,所以下一個漸層顏色會自動被設為起始位置顏色,因此即使我們沒有指定漸層起始位置顏色也沒有關係,就像本範例自動會設定起始位置的顏色等於位置 0.5 的黑色。 | Screenshot | Live sample | | --- | --- | | | | ### `createRadialGradient` 範例 這邊我們定義了四種放射狀漸層,相較於一般在 Photoshop 看到的「經典」放射狀漸層圖案(漸層從一個圖案中心點向外呈圓心狀延伸),因為我們可以控制漸層起始和終止點,我們可以做到更好的效果。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // Create gradients var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30); radgrad.addColorStop(0, "#A7D30C"); radgrad.addColorStop(0.9, "#019F62"); radgrad.addColorStop(1, "rgba(1,159,98,0)"); var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50); radgrad2.addColorStop(0, "#FF5F98"); radgrad2.addColorStop(0.75, "#FF0188"); radgrad2.addColorStop(1, "rgba(255,1,136,0)"); var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40); radgrad3.addColorStop(0, "#00C9FF"); radgrad3.addColorStop(0.8, "#00B5E2"); radgrad3.addColorStop(1, "rgba(0,201,255,0)"); var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90); radgrad4.addColorStop(0, "#F4F201"); radgrad4.addColorStop(0.8, "#E4C700"); radgrad4.addColorStop(1, "rgba(228,199,0,0)"); // draw shapes ctx.fillStyle = radgrad4; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad3; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad2; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad; ctx.fillRect(0, 0, 150, 150); } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 程式碼範例中,為了營造出 3D 效果,我們讓起始點和終止點位於不同位置,請注意,最好不要讓內外圈相重疊,以避免難以預測的奇怪效果。 每一個漸層圖案最後一個漸層色都是全透明的,如果希望倒數第二個漸層色能夠平順地轉換到這個最後一個漸層色,那麼兩者應該設定一樣的顏色值,像是程式碼範例中的漸層色 #019F62 其實就等於 rgba(1,159,98,1)。 | Screenshot | Live sample | | --- | --- | | | | 樣式(Patterns) ------------ 先前的範例中,我們都是藉由迴圈來重複產生影像樣式,不過其實有一條更簡單的方法,那就是呼叫 createPattern 方法。 `createPattern(image, type)` 呼叫 createPattern()會產一個畫布樣式物件,然後回傳出來。 其中 image 是CanvasImageSource類別物件(像是`HTMLImageElement` (en-US),、<canvas>元素、`<video>` (en-US) 元素等) Type 是一串字串,定義了如何產生樣式,允許的值有: `repeat` 沿垂直與水平方向重複排列影像 `repeat-x` 只沿水平方向重複排列影像 `repeat-y` 只沿垂直方向重複排列影像 `no-repeat` 不重複排列影像,只使用一次 **備註:** Firefox 現在只支援 repeat,所以其他值都是無效的 **備註:** 傳入尺寸為 0x0 像素的畫布會引起錯誤 利用 createPattern()的方法和前面利用漸層的方法十分類似,我們呼叫 createPattern()產生`CanvasPattern` (en-US)物件,然後將{CanvasPattern}物件設成 fillStyle 或 strokeStyle 的屬性值,例如: ```js var img = new Image(); img.src = "someimage.png"; var ptrn = ctx.createPattern(img, "repeat"); ``` **備註:** 不像 drawImage()方法,呼叫 createPattern()方法前影像必須要先載入完成,否則可能圖像的程生會有問題。 ### `createPattern` 範例 這個範例中我們把 fillStyle 屬性值存為樣式物件,比較值得注意的是影像 onload 事件處理器,這是為了確保影像載入完成後再進行。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); // create new image object to use as pattern var img = new Image(); img.src = "/files/222/Canvas\_createpattern.png"; img.onload = function () { // create pattern var ptrn = ctx.createPattern(img, "repeat"); ctx.fillStyle = ptrn; ctx.fillRect(0, 0, 150, 150); }; } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` draw(); ``` 結果如下 : | Screenshot | Live sample | | --- | --- | | | | 陰影 -- 要產生陰影只需要四個屬性: `shadowOffsetX = float` 代表陰影從物件延伸出來的水平距離,預設為 0,不受變形矩陣影響。 `shadowOffsetY = float` 代表陰影從物件延伸出來的垂直距離,預設為 0,不受變形矩陣影響。 `shadowBlur = float` 代表陰影模糊大小範圍,預設為 0,不受變形矩陣影響,不等同於像素值。 `shadowColor = `<color>` (en-US)` CSS 顏色值,代表陰影顏色,預設為全透明。 `shadowOffsetX和shadowOffsetY會決定陰影延伸大小,若是為正值,則陰影會往右(沿X軸)和往下(沿Y軸)延伸,若是為負值,則會往正值相反方向延伸。` **備註:** 基於 HTML5 提議規格變更,從 開始,陰影只會在 source-over 的構圖排列下產生 ### 文字陰影範例 本程式碼範例會產生一串帶有陰影的文字。 ```js function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 2; ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; ctx.font = "20px Times New Roman"; ctx.fillStyle = "Black"; ctx.fillText("Sample String", 5, 30); } ``` ``` <canvas id="canvas" width="150" height="80"></canvas> ``` ``` draw(); ``` | Screenshot | Live sample | | --- | --- | | | | * « 前頁 * 次頁 »
基礎動畫 - Web APIs
基礎動畫 ==== * « 前頁 * 次頁 » 控制`<canvas>`元素來產生互動式動畫不是一件難事,當然,如果產生的動畫越複雜越需要多費一些力氣,未來如果有機會我們將說明這一塊。 由於圖形一但產生後便靜止不動,所以我們必須重新繪圖好移動圖案,產生動畫效果,所以如果繪圖越複雜,繪圖運算也需要消耗越多運算資源和時間,換句話說,電腦效能的好壞將大大影響動畫順暢度,或許這也是畫布動畫最大的限制。 動畫基本步驟 ------ 產生一個畫面基本上需要以下步驟: 1. **清除畫布** 除了不變的背景畫面,所有先前畫的圖案都要先清除,這個步驟可以透過 `clearRect()` 方法達成。 2. **儲存畫布狀態** 若是想要每一次重新繪圖時畫布起始狀態都是原始狀態,那麼就需要先行儲存畫布原始狀態。 3. **畫出畫面** 畫出需要畫面。 4. **復原畫布狀態** 復原畫布狀態以備下次繪圖使用。 控制動畫 ---- 一般來說當程式碼執行完畢後我們才會看到繪圖結果,所以說我們無法靠執行 for 迴圈來產生動畫,我們得靠每隔一段時間繪圖來產生動畫,下面將介紹兩種作法。 ### 排程更新 第一種作法是利用 `window.setInterval()` (en-US) 與 `window.setTimeout()` (en-US) 方法。 **備註:** 針對新版瀏覽器建議採用 `window.requestAnimationFrame()` 方法。 `setInterval(function, delay)` 每隔 delay 毫秒,執行輸入 function(函數) `setTimeout(function, delay)` 過 delay 毫秒後,執行輸入 function(函數) requestAnimationFrame(callback) 告訴瀏覽器你希望執行動畫的時候,要求瀏覽器在重繪下一張畫面之前,呼叫 callback 函數來更新動畫 如果希望不要有任何的使用者互動影響,請使用 setInterval(),因為它會確實地每隔一段時間就執行程式碼。如果你想製作遊戲,我們能夠使用 keyboard 或是 mouse event 來控制動畫,並使用 setTimeout() 函數一起。藉由設定 EventListeners,我們能夠捕捉任何使用者的動作,並執行我們的動畫函數。 **備註:** 在下面的範例,我們將使用 **`window.requestAnimationFrame()`** 方法來控制動畫,**`window.requestAnimationFrame()`** 方法為動畫提供更順暢更有效率的方式來執行,當系統準備好繪製畫面時,藉由呼叫動畫 andmation frame() 的 callback 函數。callback 通常每秒鐘執行 60 次,當執行 background tab 時,執行次數會更低,想知道更多關於動畫迴圈(animation loop)的資訊,尤其是遊戲的應用,請查看我們在 Game development zone 的主題 Anatomy of a video game (en-US)。 ### 從使用者輸入操作控制動畫 我們也可以從使用者輸入操作控制動畫,就像是電玩遊戲一般;像是在鍵盤上設置事件處理器 `EventListener` 捕捉使用者輸入並執行對應動畫。 你可以利用我們的次要版 (en-US)或主要版動畫框架。 ```js var myAnimation = new MiniDaemon(null, animateShape, 500, Infinity); ``` 或 ```js var myAnimation = new Daemon(null, animateShape, 500, Infinity); ``` 在後面的範例我們主要將使用 window.setInterval()方法控制動畫,然後於本頁底部是一些使用 widnow.setTimeout()的範例連結。 #### 太陽系動畫 本例會產生一個小型太陽系運行動畫。 ```js var sun = new Image(); var moon = new Image(); var earth = new Image(); function init() { sun.src = "canvas\_sun.png"; moon.src = "canvas\_moon.png"; earth.src = "canvas\_earth.png"; setInterval(draw, 100); } function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.globalCompositeOperation = "destination-over"; ctx.clearRect(0, 0, 300, 300); // clear canvas ctx.fillStyle = "rgba(0,0,0,0.4)"; ctx.strokeStyle = "rgba(0,153,255,0.4)"; ctx.save(); ctx.translate(150, 150); // Earth var time = new Date(); ctx.rotate( ((2 \* Math.PI) / 60) \* time.getSeconds() + ((2 \* Math.PI) / 60000) \* time.getMilliseconds(), ); ctx.translate(105, 0); ctx.fillRect(0, -12, 50, 24); // Shadow ctx.drawImage(earth, -12, -12); // Moon ctx.save(); ctx.rotate( ((2 \* Math.PI) / 6) \* time.getSeconds() + ((2 \* Math.PI) / 6000) \* time.getMilliseconds(), ); ctx.translate(0, 28.5); ctx.drawImage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginPath(); ctx.arc(150, 150, 105, 0, Math.PI \* 2, false); // Earth orbit ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300); } ``` ``` <canvas id="canvas" width="300" height="300"></canvas> ``` ``` init(); ``` #### 時鐘動畫 本例會產生一個時鐘指向現在時間。 ```js function init() { clock(); setInterval(clock, 1000); } function clock() { var now = new Date(); var ctx = document.getElementById("canvas").getContext("2d"); ctx.save(); ctx.clearRect(0, 0, 150, 150); ctx.translate(75, 75); ctx.scale(0.4, 0.4); ctx.rotate(-Math.PI / 2); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.lineWidth = 8; ctx.lineCap = "round"; // Hour marks ctx.save(); for (var i = 0; i < 12; i++) { ctx.beginPath(); ctx.rotate(Math.PI / 6); ctx.moveTo(100, 0); ctx.lineTo(120, 0); ctx.stroke(); } ctx.restore(); // Minute marks ctx.save(); ctx.lineWidth = 5; for (i = 0; i < 60; i++) { if (i % 5 != 0) { ctx.beginPath(); ctx.moveTo(117, 0); ctx.lineTo(120, 0); ctx.stroke(); } ctx.rotate(Math.PI / 30); } ctx.restore(); var sec = now.getSeconds(); var min = now.getMinutes(); var hr = now.getHours(); hr = hr >= 12 ? hr - 12 : hr; ctx.fillStyle = "black"; // write Hours ctx.save(); ctx.rotate( hr \* (Math.PI / 6) + (Math.PI / 360) \* min + (Math.PI / 21600) \* sec, ); ctx.lineWidth = 14; ctx.beginPath(); ctx.moveTo(-20, 0); ctx.lineTo(80, 0); ctx.stroke(); ctx.restore(); // write Minutes ctx.save(); ctx.rotate((Math.PI / 30) \* min + (Math.PI / 1800) \* sec); ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(-28, 0); ctx.lineTo(112, 0); ctx.stroke(); ctx.restore(); // Write seconds ctx.save(); ctx.rotate((sec \* Math.PI) / 30); ctx.strokeStyle = "#D40000"; ctx.fillStyle = "#D40000"; ctx.lineWidth = 6; ctx.beginPath(); ctx.moveTo(-30, 0); ctx.lineTo(83, 0); ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, 10, 0, Math.PI \* 2, true); ctx.fill(); ctx.beginPath(); ctx.arc(95, 0, 10, 0, Math.PI \* 2, true); ctx.stroke(); ctx.fillStyle = "rgba(0,0,0,0)"; ctx.arc(0, 0, 3, 0, Math.PI \* 2, true); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.lineWidth = 14; ctx.strokeStyle = "#325FA2"; ctx.arc(0, 0, 142, 0, Math.PI \* 2, true); ctx.stroke(); ctx.restore(); } ``` ``` <canvas id="canvas" width="150" height="150"></canvas> ``` ``` init(); ``` #### 循環景色 本例會產一個由左到右循環捲動美國優勝美地國家公園景色,你也可以自行替換其他比畫布還大的圖片。 ```js var img = new Image(); // User Variables - customize these to change the image being scrolled, its // direction, and the speed. img.src = "/files/4553/Capitan\_Meadows,\_Yosemite\_National\_Park.jpg"; var CanvasXSize = 800; var CanvasYSize = 200; var speed = 30; //lower is faster var scale = 1.05; var y = -4.5; //vertical offset // Main program var dx = 0.75; var imgW; var imgH; var x = 0; var clearX; var clearY; var ctx; img.onload = function () { imgW = img.width \* scale; imgH = img.height \* scale; if (imgW > CanvasXSize) { x = CanvasXSize - imgW; } // image larger than canvas if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas else { clearX = CanvasXSize; } if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas else { clearY = CanvasYSize; } //Get Canvas Element ctx = document.getElementById("canvas").getContext("2d"); //Set Refresh Rate return setInterval(draw, speed); }; function draw() { //Clear Canvas ctx.clearRect(0, 0, clearX, clearY); //If image is <= Canvas Size if (imgW <= CanvasXSize) { //reset, start from beginning if (x > CanvasXSize) { x = 0; } //draw aditional image if (x > CanvasXSize - imgW) { ctx.drawImage(img, x - CanvasXSize + 1, y, imgW, imgH); } } //If image is > Canvas Size else { //reset, start from beginning if (x > CanvasXSize) { x = CanvasXSize - imgW; } //draw aditional image if (x > CanvasXSize - imgW) { ctx.drawImage(img, x - imgW + 1, y, imgW, imgH); } } //draw image ctx.drawImage(img, x, y, imgW, imgH); //amount to move x += dx; } ``` 循環景色就是在下方的`<canvas>`中捲動,請注意其中的 width 和 height 和程式碼中的 CanvasXZSize 與 CanvasYSize 一樣。 ```html <canvas id="canvas" width="800" height="200"></canvas> ``` ##### 結果 其他範例 ---- Gartic 多人繪圖遊戲 Canvascape 第一人稱 3D 冒險遊戲 A basic ray-caster 透過鍵盤控制動畫範例 canvas adventure 另一個透過鍵盤控制動畫範例 An interactive Blob 和 Blob 遊戲 Flying through a starfield 飛越星河 iGrapher 股票市場圖 See also -------- * JavaScript timers * `setInterval` – A little framework (en-US) * JavaScript Daemons Management * HTMLCanvasElement (en-US) * « 前頁 * 次頁 » (en-US)
控制畫面方向 - Web APIs
控制畫面方向 ====== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 摘要 -- 畫面方向(Screen Orientation)與裝置方向(Device Orientation) (en-US)略有不同。有時甚至裝置本身不具備方向偵測功能,但裝置的螢幕仍搭載方向功能。如果裝置可測知本身的方向又能控制畫面方向,就能隨時配合 Web Apps 而達到最佳效果。 現有 2 種方法可處理畫面的方向,但均需搭配 CSS 與 JavaScript。第一種方法就是方向的 Media Query (en-US)。根據瀏覽器視窗為橫放(寬度大於高度)或直放(高度大於寬度)狀態,而透過 CSS 調整網頁內容的配置。 第二種方法就是 JavaScript Screen Orientation API,可取得畫面目前的方向並進一步鎖定。 根據方向而調整配置 --------- 方向改變最常見的情形之一,就是根據裝置的方向而修正內容的配置方式。舉例來說,你可能想將按鈕列拉到與裝置螢幕等長。而透過 Media Query 即可輕鬆達到此效果。 來看看下列 HTML 程式碼範例: ```html <ul id="toolbar"> <li>A</li> <li>B</li> <li>C</li> </ul> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. Nullam quis malesuada est. </p> ``` CSS 將根據方向的 Media Query,處理畫面方向的特殊樣式: ```css /\* First let's define some common styles \*/ html, body { width: 100%; height: 100%; } body { border: 1px solid black; -moz-box-sizing: border-box; box-sizing: border-box; } p { font: 1em sans-serif; margin: 0; padding: 0.5em; } ul { list-style: none; font: 1em monospace; margin: 0; padding: 0.5em; -moz-box-sizing: border-box; box-sizing: border-box; background: black; } li { display: inline-block; margin: 0; padding: 0.5em; background: white; } ``` 在設定某些通用的樣式之後,即可針對方向定義特殊條件: ```css /\* For portrait, we want the tool bar on top \*/ @media screen and (orientation: portrait) { #toolbar { width: 100%; } } /\* For landscape, we want the tool bar stick on the left \*/ @media screen and (orientation: landscape) { #toolbar { position: fixed; width: 2.65em; height: 100%; } p { margin-left: 2em; } li + li { margin-top: 0.5em; } } ``` 結果如下所示(若無法顯示,可至本文右上角切換回英文原文觀看): | Portrait | Landscape | | --- | --- | | | | **備註:** 方向 Media Query 其實是以瀏覽器視窗 (或 iframe) 的方向為準,而非裝置本身的方向。 鎖定畫面方向 ------ **警告:** 此 API 仍屬實驗性質,目前仍具備 `moz` 前綴而僅能用於 Firefox OS 與 Firefox for Android,而 Windows 8.1 以上版本的 Internet Explorer 則使用 `ms` 前綴。 某些裝置(主要為行動裝置)可根據本身方向而動態改變畫面的方向,讓使用者隨時閱讀畫面上的資訊。這種動作對文字類的內容影響不大,但某些內容就無法順利套用此功能。舉例來說,若遊戲需要裝置方向的相關資訊,就可能因為方向變化而發生混亂情形。 而 Screen Orientation API 即可用以避免或處理這類變化。 ### 監聽方向變化 只要裝置改變了畫面方向與本身方向,就會觸發 `orientationchange` 事件,再由 `Screen.orientation` 屬性讀取之。 ```js screen.addEventListener("orientationchange", function () { console.log("The orientation of the screen is: " + screen.orientation); }); ``` ### 避免方向改變 任何 Web Apps 均可鎖定畫面以符合本身需求。`Screen.lockOrientation()` (en-US) 函式可鎖定畫面方向;`Screen.unlockOrientation()` (en-US) 函式可解鎖畫面方向。 `Screen.lockOrientation()` (en-US) 將接受一組字串或系列字串,以定義畫面鎖定的方向。有效字串為:「`portrait-primary`」、「`portrait-secondary`」、「`landscape-primary`」、「`landscape-secondary`」、「`portrait`」、「`landscape`」。另可參閱 `Screen.lockOrientation` (en-US) 進一步了解這些有效值。 ```js screen.lockOrientation("landscape"); ``` **備註:** 畫面鎖定功能將依 Web Apps 而有所不同。如果 App A 鎖定為 `landscape`;App B 鎖定為 `portrait,則此兩款 Apps 均將維持自己的方向。所以不論如何切換` A 與 B,均不會觸發 `orientationchange` 事件。但若必須改變方向以滿足畫面鎖定的需求,則鎖定方向時就會觸發 `orientationchange` 事件。 Firefox OS and Android: Orientation lock using the manifest ----------------------------------------------------------- For a Firefox OS and Firefox Android (soon to work on Firefox desktop too) specific way to lock orientation, you can set the orientation field in app's your manifest file, for example: ```json "orientation": "portrait" ``` 參見 -- * `Screen.orientation` * `Screen.lockOrientation()` (en-US) * `Screen.unlockOrientation()` (en-US) * `Screen.onorientationchange` (en-US) * 方向的 Media Query (en-US) * Firefox 3.5 的 Media Queries 簡介
使用IndexedDB - Web APIs
使用IndexedDB =========== IndexedDB 提供了在瀏覽器上儲存保留資料的功能,藉由它,不論是線上或線下我們的應用都可以進行資料存取。 關於本文 ---- 本文會帶領各位操作非同步 IndexedDB 的 API,如果不知道甚麼是 IndexedDB,請先看看"IndexedDB 基本礎念"。 基本操作步驟 ------ 操作 IndexedDB 的基本步驟建議如下: 1. 開啟資料庫和交易(transaction)。 2. 建立物件存檔(object store) 3. 發出資料庫操作請求,例如新增或取得資料。 4. 聆聽對應 DOM 事件等待操作完成。 5. 從 result 物件上取得結果進行其他工作。 好了,知道了上述概念後,我們可以來實際做些甚麼。 建立和結構資料庫 -------- 由於 IndexedDB 的標準仍在演進,所以目前一些實作還需要加上瀏覽器前綴標示(如 Gecko 基礎瀏覽器的前綴標示為 moz,WebKit 基礎瀏覽器的前綴標示為 webkit),瀏覽器的實作也可能會有所差異,不過一旦共識標準達成,無瀏覽器前綴標示實作將出現。其實,Internet Explorer 10, Firefox 16, Chrome 24 已經有了無瀏覽器前綴標示實作。 ### 操作實驗性質的 IndexedDB 如果需要試驗瀏覽器的前綴標示,可以如下: ```js // In the following line, you should include the prefixes of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB\* objects: window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; // (Mozilla has never prefixed these objects, so we don't need window.mozIDB\*) ``` 請注意瀏覽器前綴標示的實作可能不完整、有些問題或仍然遵守舊版標準,因此不建議在正式版程式碼中使用。與其宣稱支援又有問題,倒不如直接不支援。 ```js if (!window.indexedDB) { window.alert( "Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.", ); } ``` ### 開啟資料庫 開頭如下: ```js // Let us open our database var request = window.indexedDB.open("MyTestDatabase", 3); ``` 注意到了嗎,開啟資料庫必須要進行請求。 開啟請求並不會立刻開啟資料庫或交易,呼叫 open()方法會回傳一個`IDBOpenDBRequest` (en-US)物件,這個物件擁有兩個事件(success 和 error)。大部分 IndexedDB 的非同步功能都會回傳一個`IDBDatabase` (en-US)類物件,然後我們可以註冊成功和失敗事件處理器。 Open 方法第二個參數是資料庫版本,資料庫版本決定了資料庫結構,也就是資料庫物件存檔的結構。如果請求版本不存在(比如因為這是一個新資料庫或是資料庫版本已升級),onupgradeneeded 事件會被觸發,然後我們可以在 onupgradeneeded 事件處理器中再建立新的版本,下面升級資料庫版本有更詳細的說明。 #### 產生事件處理器 幾乎所有第一件要對請求做的事都是產生 success 和 error 事件處理器: ```js request.onerror = function (event) { // Do something with request.errorCode! }; request.onsuccess = function (event) { // Do something with request.result! }; ``` 如果一切正常,success 事件(也就是 DOM 事件的 type 屬性設為 success)會以 request 為目標觸發,然後 request 物件上的 onsuccess 函數接著被呼叫,其中 success 事件就是參數;否則 error 事件(也就是 DOM 事件的 type 屬性設為 error)會以 request 為目標觸發,然後 request 物件上的 onerror 函數接著被呼叫,其中 error 事件就是參數。 IndexedDB 的 API 設計上盡量減少錯誤處理,所以不太常看到錯誤事件,不過開啟資料庫的時候還是有一些狀況會產產生錯誤,最常見的狀況是使用者拒絕我們建立資料庫。 IndexedDB 設計目標之一為存放大量資料以供離線使用(請參考"儲存限制"了解更多細節)。但很明顯地,瀏覽器又不樂見一些廣告網站或惡意網站汙染電腦,所以當任一個網路應用第一次開啟 IndexedDB 資料庫,瀏覽器會徵詢使用者是否准許其作業;同時在私密瀏覽中開啟作業也會失敗,因為私密瀏覽不會留下任何瀏覽痕跡。 這裡呼叫 indexedDB.open()開啟 indexedDB 資料庫並回傳 request 物件,假設使用者允許我們建立 indexedDB 資料庫,我們也收到 suceess 事件觸發了 success 回呼函數(callback),request 物件的 result 屬性會是一個 IDBDatabase 物件 ,接下來便是要儲存這個物件之後使用。下方是整個作業的示範程式碼: ```js var db; var request = indexedDB.open("MyTestDatabase"); request.onerror = function (event) { alert("Why didn't you allow my web app to use IndexedDB?!"); }; request.onsuccess = function (event) { db = request.result; }; ``` #### 錯誤處理 錯誤事件會向上傳遞;錯誤事件以產生錯誤之請求為目標觸發,然後一路傳遞到交易,最後到資料庫物件;如果不想要為每一個請求新增錯誤處理器,可以改為資料庫物件加入一個錯誤處理器。 ```js db.onerror = function (event) { // Generic error handler for all errors targeted at this database's // requests! alert("Database error: " + event.target.errorCode); }; ``` 最常見的錯誤之一就是 VER\_ERR,該錯誤代表現在資料料庫版本大於嘗試開啟的資料庫版本,這項錯誤必須要有錯誤處理器處理。 ### 建立或更新資料庫版本 新版本資料庫建立會觸發 onupgradeneeded 事件,在這個事件的處理器中要建立這個版本資料庫需要的物件存檔。 ```js // This event is only implemented in recent browsers request.onupgradeneeded = function (event) { var db = event.target.result; // Create an objectStore for this database var objectStore = db.createObjectStore("name", { keyPath: "myKey" }); }; ``` 資料庫版本是 unsigned long long 的數字,所以能夠非常長。 **警告:** 請注意這也意味著版本不能為浮點數,否則小數點部分將會無條件捨去,而交易也可能不會開始,upgradeneeded 事件也不會觸發。不要像以下例子以 2.4 作版本: ```js var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2 ``` 升級版本資料庫建立會觸發 onupgradeneeded 事件,這個時候資料庫裡面已經含有前版本下的物件存檔,所以說不需要再次建立這些物件存檔了,剩下的是新增或刪除物件存檔。如果想要更動既存物件存檔(例如改變資料鍵路徑),那麼會需要先刪除舊的再產生一個新的(請注意這也會刪除物件存檔裡的資料,所以如果資料需要保留的話,請在升級前先讀出資料備份。) Webkit 支援最新標準不過只有 Chrome 23 才開始導入,而較舊不支援最新版標準的版本則不支援 indexedDB.open(name, version).onupgradeneeded。關於如何在舊版標準下升級資料庫版本請參考"IDBDatabase 參考文章"。 ### 結構化資料庫 indexedDB 不用資料表而是物件存檔,物件存檔可以有很多。一筆物件存檔裡的資料值對應一筆資料鍵,依據使用{資料鍵路徑(key path)}或{資料鍵產生器(key generator)}。 下表列出資料建各類產生途徑: | Key Path | Key Generator | 描述 | | --- | --- | --- | | No | No | 物件存檔資料值能為任何型別,即使像數字或字串。每當新增一筆資料,必須提供不同的資料鍵。 | | Yes | No | 物件存檔資料值僅能為 Javacript 物件,而該資料物件必須含有和資料鍵路徑相同名稱之屬性成員。 | | No | Yes | 物件存檔資料值能為任何型別,資料鍵自動產生,但如果想要指定資料鍵也可以另外提供資料鍵。 | | Yes | Yes | 物件存檔資料值僅能為 Javascript 物件。通常被產生的新資料鍵的值會被存在物件屬性名稱和資料鍵路徑名稱相同的物件屬性下,如果這個屬性已經存在,這個已經存在之屬性之值將被用作為資料鍵,而非新產生的資料鍵。 | 我們可以替任何儲存資料為物件型態而非原始資料型態的物件存檔建立索引,索引讓我們能夠用物件存檔中資料物件內的某一個屬性值查找資料,而非僅僅物件的資料鍵。 除此之外,利用索引還可以施加簡單的儲存限制;建立索引時設定獨特旗標(flag),這個索引保證在此索引資料鍵下不會存在兩個物件存檔擁有同樣資料值,比如說現在有一個存放許多使用者的物件存檔,而且我們希望保證不會存在有兩個使用者的電子郵件地址一樣,此使索引的獨特旗標便可以幫助我們達成目標。 以上聽起來可能會有些複雜,請看一下下面的實例: ```js // This is what our customer data looks like. const customerData = [ { ssn: "444-44-4444", name: "Bill", age: 35, email: "[email protected]" }, { ssn: "555-55-5555", name: "Donna", age: 32, email: "[email protected]" }, ]; const dbName = "the\_name"; var request = indexedDB.open(dbName, 2); request.onerror = function (event) { // Handle errors. }; request.onupgradeneeded = function (event) { var db = event.target.result; // Create an objectStore to hold information about our customers. We're // going to use "ssn" as our key path because it's guaranteed to be // unique. var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. objectStore.createIndex("name", "name", { unique: false }); // Create an index to search customers by email. We want to ensure that // no two customers have the same email, so use a unique index. objectStore.createIndex("email", "email", { unique: true }); // Store values in the newly created objectStore. for (var i in customerData) { objectStore.add(customerData[i]); } }; ``` 請注意 onupgradeneeded 事件是唯一能夠變更資料庫結構之處,在此事件才能建立或刪除物件存檔以及建立和刪除索引。 呼叫IDBDatabase類別物件的 createObjectStore 方法會立刻創造一個物件存檔,這個方法接收兩個參數,一個是物件存檔名稱,一個是非必填的參數物件,雖然參數物件不為必填但是卻相當重要,因為它讓我們定義了一些重要屬性(請參考createObjectStore)。本例中我們要求建立了一個"customer"物件存檔,定義"ssn"屬性為資料件路徑,使用"ssn"作為資料鍵路徑是因為每個客戶的 ssn 碼一定是獨立的。一旦決定了"ssn"作為資料鍵路徑,那麼每一筆資料一定要含有"ssn"。 本例還創建一個稱為"name"的索引,"name"索引查找目標為資料的"name"屬性,且不設立其獨特旗標(unique 為 false),同樣地,我們又呼叫createIndex方法創建了一個"email"索引,不過"email"索引具備獨特旗標(unique 為 true)。雖然存在"name"索引,但資料不一定要含有"name"屬性,只是當搜索"name"索引時資料不會出現。 接下來我們可以開始用 ssn 從物件存檔中取出資料,或是用索引找出資料(請參考使用索引)。 ### 使用資料鍵產生器 當建立物件存檔時設定 autoIncrement 旗標為 ture 將啟動資料鍵產生器,預設上該旗標為 false。 有了資料鍵產生器,當新增資料到物件存檔中,資料鍵產生器會自動幫我們產生資料鍵。資料鍵產生器產生的資料鍵由整數 1 開始,而基本上新產生的資料鍵是由前一個資料鍵加 1 產生。資料鍵的產生不會因為資料刪除或清空所有資料而重新開始起算,所以資料鍵值是一直累加上去的,除非資料庫操作中斷,整個交易作業被取消。 我們可以建立一個有資料鍵產生器的物件存檔如下: ```js // Open the indexedDB. var request = indexedDB.open(dbName, 3); request.onupgradeneeded = function (event) { var db = event.target.result; // Create another object store called "names" with the autoIncrement flag set as true. var objStore = db.createObjectStore("names", { autoIncrement: true }); // Because the "names" object store has the key generator, the key for the name value is generated automatically. // The added records would be like: // key : 1 => value : "Bill" // key : 2 => value : "Donna" for (var i in customerData) { objStore.add(customerData[i].name); } }; ``` 關於資料鍵產生器細節,請參考"W3C Key Generators"。 新增和刪除資料 ------- 在操作資料庫之前必須要先進行交易,交易來自資料庫物件,在交易中要指定涵蓋物件存檔範圍,然後也要決定是要變更資料庫或純粹讀取資料。交易共有三種種類,分別是讀取(read-only),讀寫(read/write), 以及版本變更(versionchange),如果只需要讀資料最好只使用讀取(read-only)交易,因為讀取(read-only)交易可以多重同步進行。 ### 新增資料到資料庫 創建資料庫後,如果要寫入資料請這麼做: ```js var transaction = db.transaction(["customers"], "readwrite"); // Note: Older experimental implementations use the deprecated constant IDBTransaction.READ\_WRITE instead of "readwrite". // In case you want to support such an implementation, you can just write: // var transaction = db.transaction(["customers"], IDBTransaction.READ\_WRITE); ``` 呼叫transaction() (en-US)方法會回傳一個交易物件。transaction()第一個接受參數代表交易涵蓋的物件存檔,雖然傳入空陣列會讓交易涵蓋所有物件存檔,但請不要這麼做,因為根據正式標準傳入空陣列應該要導致 InvalidAccessError 錯誤;第二個參數代表交易種類,不傳入的話預設為讀取交易,本例要寫入資料庫所以傳入讀寫("readwrite")。 交易的生命週期和事件循環關係密切。當我們發起交易又回到事件循環中後,如果忽略,那麼交易將轉成結束,唯一保持交易存活的方法是在交易上發出請求;當請求完成後我們會收到 DOM 事件,假設請求結果成功,我們可以在事件的回呼函數(callback 中)繼續進行交易,反之,如果我們沒有繼續進行交易,那麼交易將結束,也就是說只要尚有未完成請求的話,交易就會繼續存活,如果收到 TRANSACTION\_INACTIVE\_ERR 錯誤那便意謂著交易早已結束,我們錯過了繼續進行交易的機會。 交易能收到三種事件: 錯誤(error)、中斷(abort)以及完成(complete),其中錯誤事件會向上傳遞,所以任何一個交易下轄的請求產生錯誤事件,該交易都會收到。如果交易收到錯誤事件時,瀏覽器預設行為會中斷交易,除非我們有在錯誤事件上呼叫 preventDefault()阻擋瀏覽器預設行動,否則整筆交易都將取消、復原,這樣的設計告訴我們必須要思考如何處裡錯誤,或者說如果對每一個錯誤進行處裡過於麻煩,那麼至少加入一個概括性的錯誤處理器也是可以。只要不處裡錯誤或呼叫 abort(),交易將取消、復原,然後中斷事件接著觸發,反之,當所有請求都完成後,我們會收到一個完成事件,所以說如果我們同時發起多項請求時,可以只追蹤單一交易而非個別請求,這樣會大大減輕我們的負擔。 有了交易之後便能夠從中取得物件存檔,有了物件存檔便能夠新增資料(請注意唯有在建立交易時指定的物件存檔能夠取得)。 ```js // Do something when all the data is added to the database. transaction.oncomplete = function (event) { alert("All done!"); }; transaction.onerror = function (event) { // Don't forget to handle errors! }; var objectStore = transaction.objectStore("customers"); for (var i in customerData) { var request = objectStore.add(customerData[i]); request.onsuccess = function (event) { // event.target.result == customerData[i].ssn; }; } ``` 呼叫add (en-US)方法可以加入一筆新資料,呼叫後會回傳一個IDBRequest物件,即為上方範例中的 request,如果新增成功,request 的成功事件會被觸發,而成功事件物件中有一個 result 屬性,這個 result 值剛好就等於新資料的資料鍵,所以說上方範例中的 event.target.result 剛好就等於顧客的 ssn 值(因為我們用 ssn 屬性作為資料鍵路徑)。請注意 add 方法只在當物件存檔中沒有相同資料鍵資料存在時有用,如果想要更動或是直接覆蓋現存資料請呼叫put (en-US)方法。 移除資料 ---- 移除資料十分容易: ```js var request = db .transaction(["customers"], "readwrite") .objectStore("customers") .delete("444-44-4444"); request.onsuccess = function (event) { // It's gone! }; ``` 讀取資料 ---- 要圖取資料庫內的資料有數種途徑,第一個最簡單的途徑就是提供資料鍵,呼叫get (en-US)方法取得資料: ```js var transaction = db.transaction(["customers"]); var objectStore = transaction.objectStore("customers"); var request = objectStore.get("444-44-4444"); request.onerror = function (event) { // Handle errors! }; request.onsuccess = function (event) { // Do something with the request.result! alert("Name for SSN 444-44-4444 is " + request.result.name); }; ``` 假設我們把錯誤處理放在資料庫層級,我們可以再縮短上面的程式碼如下: ```js db .transaction("customers") .objectStore("customers") .get("444-44-4444").onsuccess = function (event) { alert("Name for SSN 444-44-4444 is " + event.target.result.name); }; ``` 呼叫 transcation 方法而不指定模式會開啟讀取(readonly)模式,接著取得我們的目標物件存檔,輸入目標資料的資料鍵,呼叫 get 方法取得請求物件,然後在請求物件上註冊成功事件處理器,當作業成功後,成功事件會觸發,成功事件的物件中含有請求物件(event.target 如上述範例),請求物件中含有請求結果(event.target.result 如上述範例)。 使用指標(Cursor) ------------ 使用 get 方法需要知道資料鍵,如果想要一一存取物件存檔中的資料,我們可以利用指標: ```js var objectStore = db.transaction("customers").objectStore("customers"); objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { alert("Name for SSN " + cursor.key + " is " + cursor.value.name); cursor.continue(); } else { alert("No more entries!"); } }; ``` openCursor (en-US)方法第一個參數用來接受資料鍵範圍物件來限制存取資料範圍,第二個參數用來指定存取進行方向,像上面的範例程式便是以資料鍵由小到大之方向存取資料;呼叫 openCursor 方法後一樣會回傳一個請求物件,成功時成功事件會觸發,不過這裡有些地方要特別注意,當成功事件處裡函數被喚起時,指標物件(cursor)會存放在 result 屬性內(亦即上述 event.target.result),cursor 物件下有兩個屬性,key 屬性是資料鍵,value 屬性是資料值,如果要取得下一份資料就呼叫 cursor 的 continue()方法,然後 cursor 物件就會指向下一份資料,當沒有資料時,cursor 會是 undefined,當請求一開始便找沒有資料,result 屬性也會是 undefined。 以下用 cursor 存取一遍資料後放在陣列中的作法相當常見: ```js var customers = []; objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); } else { alert("Got all customers: " + customers); } }; ``` **警告:** 以下範例不是 IndexedDB 標準! Mozilla 瀏覽器自己做了一個 getAll()方法來方便一次取得所有 cursor 下的資料值,這個方法相當方便,不過請小心未來它有可能會消失。以下程式碼的效果和上面的一樣: ```js objectStore.getAll().onsuccess = function (event) { alert("Got all customers: " + event.target.result); }; ``` 一一檢查 cursor 的 value 屬性較不利性能表現,因為物件是被動一一建立,然而呼叫 getAll(),Gecko 一定要一次建立所有物件,所以如果想要一次取得所有物件的資料值陣列使用 getAll()比較好,如果想要一一檢查每筆資料則請利用 cursor 的方法。 ### 使用索引 利用一定唯一的 ssn 碼作為資料鍵相當合乎邏輯(隱私權的問題先擱置一放,不在本文探討範圍)。不過當我們想要查詢使用者的名字的時候,如果沒有索引就需要一一檢查每一筆資料,十分沒有效率,所以我們可以建立 name 的索引。 ```js var index = objectStore.index("name"); index.get("Donna").onsuccess = function (event) { alert("Donna's SSN is " + event.target.result.ssn); }; ``` 因為 name 不是唯一值,所以可能會有多筆資料符合"Donna"名字,此時呼叫 get()會取得資料鍵最小值的資料。 如果我們想要查看特定名字下所有的資料,可以利用 cursor。有兩種 cursor 能用在索引上,第一種一般 cursor 會比對索引值並回傳整份資料(物件存檔中的物件),第二種資料鍵 cursor 則只會回傳資料鍵值,請參考下方範例比較兩者差異: ```js index.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key is a name, like "Bill", and cursor.value is the whole object. alert( "Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email, ); cursor.continue(); } }; index.openKeyCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key is a name, like "Bill", and cursor.value is the SSN. // No way to directly get the rest of the stored object. alert("Name: " + cursor.key + ", SSN: " + cursor.value); cursor.continue(); } }; ``` ### 設定指標查詢範圍和方向 如果想要限定指標查詢範圍,那麼在乎叫 openCursor()或 openKeyCursor()時第一個參數要傳入IDBKeyRange物件以限制範圍。IDBKeyRange 物件能夠只聚焦在單一資料鍵上或者一段上下限區間;上下限區間可以是封閉(含界限)或開放(不含界限),請看以下範例: ```js // Only match "Donna" var singleKeyRange = IDBKeyRange.only("Donna"); // Match anything past "Bill", including "Bill" var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill"); // Match anything past "Bill", but don't include "Bill" var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true); // Match anything up to, but not including, "Donna" var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true); // Match anything between "Bill" and "Donna", but not including "Donna" var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true); index.openCursor(boundKeyRange).onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the matches. cursor.continue(); } }; ``` 有時候我們會想要由大到小查看資料而非預設由小到大方向,傳入第二個"prev"字串便能做到: ```js objectStore.openCursor(null, "prev").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. cursor.continue(); } }; ``` 由於"name"索引不具唯一性,所以一個名字下可能會出現多筆資料,此時如果想要避開這多筆資料,請傳入"nextunique"或"prevunique"做為第二個方向參數,當傳入之後,如一個名字下遇到多筆資料,則只有資料鍵最小的資料會被回傳。 ```js index.openKeyCursor(null, "nextunique").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. cursor.continue(); } }; ``` 關於可傳入的方向參數,請參考IDBCursor常數。 當網頁應用程式於瀏覽器另一個分頁開啟時變更版本 ----------------------- 請思考以下狀況: 使用者在第一個瀏覽器分頁中使用著舊版本,然後使用者又打開第二個分頁載入網頁,此時我們在新分頁需要對資料庫進行升級,所以呼叫 open()以更新版本開啟資料庫,但是由於第一個瀏覽器分頁並沒有關閉資料庫,因此第二個分頁的資料庫升級作業會被擋住。所以我們需要注意多個分頁同時開啟的狀況,每個分頁都得注意當發生資料庫升級事件時,要記得關閉資料庫,讓資料庫升級作業得以進行。實際作法如下: ```js var openReq = mozIndexedDB.open("MyTestDatabase", 2); openReq.onblocked = function (event) { // If some other tab is loaded with the database, then it needs to be closed // before we can proceed. alert("Please close all other tabs with this site open!"); }; openReq.onupgradeneeded = function (event) { // All other databases have been closed. Set everything up. db.createObjectStore(/\* ... \*/); useDatabase(db); }; openReq.onsuccess = function (event) { var db = event.target.result; useDatabase(db); return; }; function useDatabase(db) { // Make sure to add a handler to be notified if another page requests a version // change. We must close the database. This allows the other page to upgrade the database. // If you don't do this then the upgrade won't happen until the user closes the tab. db.onversionchange = function (event) { db.close(); alert("A new version of this page is ready. Please reload!"); }; // Do stuff with the database. } ``` 安全性 --- IndexedDB 遵守同源政策,所以它綁定創建它的來源網站,其他來源網站無法存取。就像對載入 `<frame>` (en-US) 和 `<iframe>` (en-US) 網頁的第三方 cookie 所設下的安全性和隱私權考量限制,IndexedDB 無法在載入 `<frame>` (en-US) 和 `<iframe>` (en-US) 網頁上運作,詳情請見 Firefox bug 595307。 瀏覽器關閉風險 ------- 當瀏覽器關閉,例如使用者按下關閉鈕,任何未完成 IndexedDB 交易都將默默中止,這些交易不會完成,錯誤事件也不會觸發。既然瀏覽器可能隨時被關閉,我們無法完全指望任何特定交易一定會完成,或是依賴錯誤事件做出相應處理,針對這種狀況,我們需要注意: 第一、每一筆交易結束後都應該要保持資料庫完整性,例如說,有一串使用者編輯項目清單正要存入資料庫,我們如果先在一個交易中清除舊清單,然後在另一個交易中存入新清單,那就會面臨到清除完就清單後,新清單存入交易還來不及回存,瀏覽器就關閉的風險,而這個時候資料庫裡面的清單資料將消失。所以比較好的做法應該是在同一筆交易中完成清除舊清單和存入新清單。 第二、永遠不要在 unload 事件中執行資料庫交易,因為如果 unload 事件是觸發在瀏覽器關閉下,任何資料庫交易都不會發生,或許,瀏覽器(或分頁)打開時讀取資料庫,更新資料庫當使用者編輯資料,當瀏覽器(或分頁)關閉時儲存資料這樣的做法比較直覺,不過資料庫的操作是非同步進行地,所以瀏覽器關閉的執行會在資料庫操作前發生,進而中斷後續非同步的資料庫交易,所以在 unload 事件中執行資料庫交易是行不通地。 事實上不論瀏覽器是否正常關閉,都沒有任何方法保證 IndexedDB 交易能夠順利完成,請見 Firefox bug 870645。 完整 IndexedDB 範例 --------------- ### HTML ```html <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <h1>IndexedDB Demo: storing blobs, e-publication example</h1> <div class="note"> <p>Works and tested with:</p> <div id="compat"></div> </div> <div id="msg"></div> <form id="register-form"> <table> <tbody> <tr> <td> <label for="pub-title" class="required"> Title: </label> </td> <td> <input type="text" id="pub-title" name="pub-title" /> </td> </tr> <tr> <td> <label for="pub-biblioid" class="required"> Bibliographic ID:<br /> <span class="note">(ISBN, ISSN, etc.)</span> </label> </td> <td> <input type="text" id="pub-biblioid" name="pub-biblioid" /> </td> </tr> <tr> <td> <label for="pub-year"> Year: </label> </td> <td> <input type="number" id="pub-year" name="pub-year" /> </td> </tr> </tbody> <tbody> <tr> <td> <label for="pub-file"> File image: </label> </td> <td> <input type="file" id="pub-file" /> </td> </tr> <tr> <td> <label for="pub-file-url"> Online-file image URL:<br /> <span class="note">(same origin URL)</span> </label> </td> <td> <input type="text" id="pub-file-url" name="pub-file-url" /> </td> </tr> </tbody> </table> <div class="button-pane"> <input type="button" id="add-button" value="Add Publication" /> <input type="reset" id="register-form-reset" /> </div> </form> <form id="delete-form"> <table> <tbody> <tr> <td> <label for="pub-biblioid-to-delete"> Bibliographic ID:<br /> <span class="note">(ISBN, ISSN, etc.)</span> </label> </td> <td> <input type="text" id="pub-biblioid-to-delete" name="pub-biblioid-to-delete" /> </td> </tr> <tr> <td> <label for="key-to-delete"> Key:<br /> <span class="note">(for example 1, 2, 3, etc.)</span> </label> </td> <td> <input type="text" id="key-to-delete" name="key-to-delete" /> </td> </tr> </tbody> </table> <div class="button-pane"> <input type="button" id="delete-button" value="Delete Publication" /> <input type="button" id="clear-store-button" value="Clear the whole store" class="destructive" /> </div> </form> <form id="search-form"> <div class="button-pane"> <input type="button" id="search-list-button" value="List database content" /> </div> </form> <div> <div id="pub-msg"></div> <div id="pub-viewer"></div> <ul id="pub-list"></ul> </div> ``` ### CSS ```css body { font-size: 0.8em; font-family: Sans-Serif; } form { background-color: #cccccc; border-radius: 0.3em; display: inline-block; margin-bottom: 0.5em; padding: 1em; } table { border-collapse: collapse; } input { padding: 0.3em; border-color: #cccccc; border-radius: 0.3em; } .required:after { content: "\*"; color: red; } .button-pane { margin-top: 1em; } #pub-viewer { float: right; width: 48%; height: 20em; border: solid #d092ff 0.1em; } #pub-viewer iframe { width: 100%; height: 100%; } #pub-list { width: 46%; background-color: #eeeeee; border-radius: 0.3em; } #pub-list li { padding-top: 0.5em; padding-bottom: 0.5em; padding-right: 0.5em; } #msg { margin-bottom: 1em; } .action-success { padding: 0.5em; color: #00d21e; background-color: #eeeeee; border-radius: 0.2em; } .action-failure { padding: 0.5em; color: #ff1408; background-color: #eeeeee; border-radius: 0.2em; } .note { font-size: smaller; } .destructive { background-color: orange; } .destructive:hover { background-color: #ff8000; } .destructive:active { background-color: red; } ``` ### JavaScript ```js (function () { var COMPAT\_ENVS = [ ["Firefox", ">= 16.0"], [ "Google Chrome", ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support", ], ]; var compat = $("#compat"); compat.empty(); compat.append('<ul id="compat-list"></ul>'); COMPAT\_ENVS.forEach(function (val, idx, array) { $("#compat-list").append("<li>" + val[0] + ": " + val[1] + "</li>"); }); const DB\_NAME = "mdn-demo-indexeddb-epublications"; const DB\_VERSION = 1; // Use a long long for this value (don't use a float) const DB\_STORE\_NAME = "publications"; var db; // Used to keep track of which view is displayed to avoid uselessly reloading it var current_view_pub_key; function openDb() { console.log("openDb ..."); var req = indexedDB.open(DB\_NAME, DB\_VERSION); req.onsuccess = function (evt) { // Better use "this" than "req" to get the result to avoid problems with // garbage collection. // db = req.result; db = this.result; console.log("openDb DONE"); }; req.onerror = function (evt) { console.error("openDb:", evt.target.errorCode); }; req.onupgradeneeded = function (evt) { console.log("openDb.onupgradeneeded"); var store = evt.currentTarget.result.createObjectStore(DB\_STORE\_NAME, { keyPath: "id", autoIncrement: true, }); store.createIndex("biblioid", "biblioid", { unique: true }); store.createIndex("title", "title", { unique: false }); store.createIndex("year", "year", { unique: false }); }; } /\*\* \* @param {string} store\_name \* @param {string} mode either "readonly" or "readwrite" \*/ function getObjectStore(store\_name, mode) { var tx = db.transaction(store_name, mode); return tx.objectStore(store_name); } function clearObjectStore(store\_name) { var store = getObjectStore(DB\_STORE\_NAME, "readwrite"); var req = store.clear(); req.onsuccess = function (evt) { displayActionSuccess("Store cleared"); displayPubList(store); }; req.onerror = function (evt) { console.error("clearObjectStore:", evt.target.errorCode); displayActionFailure(this.error); }; } function getBlob(key, store, success\_callback) { var req = store.get(key); req.onsuccess = function (evt) { var value = evt.target.result; if (value) success\_callback(value.blob); }; } /\*\* \* @param {IDBObjectStore=} store \*/ function displayPubList(store) { console.log("displayPubList"); if (typeof store == "undefined") store = getObjectStore(DB\_STORE\_NAME, "readonly"); var pub_msg = $("#pub-msg"); pub_msg.empty(); var pub_list = $("#pub-list"); pub_list.empty(); // Resetting the iframe so that it doesn't display previous content newViewerFrame(); var req; req = store.count(); // Requests are executed in the order in which they were made against the // transaction, and their results are returned in the same order. // Thus the count text below will be displayed before the actual pub list // (not that it is algorithmically important in this case). req.onsuccess = function (evt) { pub_msg.append( "<p>There are <strong>" + evt.target.result + "</strong> record(s) in the object store.</p>", ); }; req.onerror = function (evt) { console.error("add error", this.error); displayActionFailure(this.error); }; var i = 0; req = store.openCursor(); req.onsuccess = function (evt) { var cursor = evt.target.result; // If the cursor is pointing at something, ask for the data if (cursor) { console.log("displayPubList cursor:", cursor); req = store.get(cursor.key); req.onsuccess = function (evt) { var value = evt.target.result; var list_item = $( "<li>" + "[" + cursor.key + "] " + "(biblioid: " + value.biblioid + ") " + value.title + "</li>", ); if (value.year != null) list_item.append(" - " + value.year); if ( value.hasOwnProperty("blob") && typeof value.blob != "undefined" ) { var link = $('<a href="' + cursor.key + '">File</a>'); link.on("click", function () { return false; }); link.on("mouseenter", function (evt) { setInViewer(evt.target.getAttribute("href")); }); list_item.append(" / "); list_item.append(link); } else { list_item.append(" / No attached file"); } pub_list.append(list_item); }; // Move on to the next object in store cursor.continue(); // This counter serves only to create distinct ids i++; } else { console.log("No more entries"); } }; } function newViewerFrame() { var viewer = $("#pub-viewer"); viewer.empty(); var iframe = $("<iframe />"); viewer.append(iframe); return iframe; } function setInViewer(key) { console.log("setInViewer:", arguments); key = Number(key); if (key == current_view_pub_key) return; current_view_pub_key = key; var store = getObjectStore(DB\_STORE\_NAME, "readonly"); getBlob(key, store, function (blob) { console.log("setInViewer blob:", blob); var iframe = newViewerFrame(); // It is not possible to set a direct link to the // blob to provide a mean to directly download it. if (blob.type == "text/html") { var reader = new FileReader(); reader.onload = function (evt) { var html = evt.target.result; iframe.load(function () { $(this).contents().find("html").html(html); }); }; reader.readAsText(blob); } else if (blob.type.indexOf("image/") == 0) { iframe.load(function () { var img_id = "image-" + key; var img = $('<img id="' + img_id + '"/>'); $(this).contents().find("body").html(img); var obj_url = window.URL.createObjectURL(blob); $(this) .contents() .find("#" + img_id) .attr("src", obj_url); window.URL.revokeObjectURL(obj_url); }); } else if (blob.type == "application/pdf") { $("\*").css("cursor", "wait"); var obj_url = window.URL.createObjectURL(blob); iframe.load(function () { $("\*").css("cursor", "auto"); }); iframe.attr("src", obj_url); window.URL.revokeObjectURL(obj_url); } else { iframe.load(function () { $(this).contents().find("body").html("No view available"); }); } }); } /\*\* \* @param {string} biblioid \* @param {string} title \* @param {number} year \* @param {string} url the URL of the image to download and store in the local \* IndexedDB database. The resource behind this URL is subjected to the \* "Same origin policy", thus for this method to work, the URL must come from \* the same origin as the web site/app this code is deployed on. \*/ function addPublicationFromUrl(biblioid, title, year, url) { console.log("addPublicationFromUrl:", arguments); var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); // Setting the wanted responseType to "blob" // http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute xhr.responseType = "blob"; xhr.onload = function (evt) { if (xhr.status == 200) { console.log("Blob retrieved"); var blob = xhr.response; console.log("Blob:", blob); addPublication(biblioid, title, year, blob); } else { console.error( "addPublicationFromUrl error:", xhr.responseText, xhr.status, ); } }; xhr.send(); // We can't use jQuery here because as of jQuery 1.8.3 the new "blob" // responseType is not handled. // http://bugs.jquery.com/ticket/11461 // http://bugs.jquery.com/ticket/7248 // $.ajax({ // url: url, // type: 'GET', // xhrFields: { responseType: 'blob' }, // success: function(data, textStatus, jqXHR) { // console.log("Blob retrieved"); // console.log("Blob:", data); // // addPublication(biblioid, title, year, data); // }, // error: function(jqXHR, textStatus, errorThrown) { // console.error(errorThrown); // displayActionFailure("Error during blob retrieval"); // } // }); } /\*\* \* @param {string} biblioid \* @param {string} title \* @param {number} year \* @param {Blob=} blob \*/ function addPublication(biblioid, title, year, blob) { console.log("addPublication arguments:", arguments); var obj = { biblioid: biblioid, title: title, year: year }; if (typeof blob != "undefined") obj.blob = blob; var store = getObjectStore(DB\_STORE\_NAME, "readwrite"); var req; try { req = store.add(obj); } catch (e) { if (e.name == "DataCloneError") displayActionFailure( "This engine doesn't know how to clone a Blob, " + "use Firefox", ); throw e; } req.onsuccess = function (evt) { console.log("Insertion in DB successful"); displayActionSuccess(); displayPubList(store); }; req.onerror = function () { console.error("addPublication error", this.error); displayActionFailure(this.error); }; } /\*\* \* @param {string} biblioid \*/ function deletePublicationFromBib(biblioid) { console.log("deletePublication:", arguments); var store = getObjectStore(DB\_STORE\_NAME, "readwrite"); var req = store.index("biblioid"); req.get(biblioid).onsuccess = function (evt) { if (typeof evt.target.result == "undefined") { displayActionFailure("No matching record found"); return; } deletePublication(evt.target.result.id, store); }; req.onerror = function (evt) { console.error("deletePublicationFromBib:", evt.target.errorCode); }; } /\*\* \* @param {number} key \* @param {IDBObjectStore=} store \*/ function deletePublication(key, store) { console.log("deletePublication:", arguments); if (typeof store == "undefined") store = getObjectStore(DB\_STORE\_NAME, "readwrite"); // As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation // the result of the Object Store Deletion Operation algorithm is // undefined, so it's not possible to know if some records were actually // deleted by looking at the request result. var req = store.get(key); req.onsuccess = function (evt) { var record = evt.target.result; console.log("record:", record); if (typeof record == "undefined") { displayActionFailure("No matching record found"); return; } // Warning: The exact same key used for creation needs to be passed for // the deletion. If the key was a Number for creation, then it needs to // be a Number for deletion. req = store.delete(key); req.onsuccess = function (evt) { console.log("evt:", evt); console.log("evt.target:", evt.target); console.log("evt.target.result:", evt.target.result); console.log("delete successful"); displayActionSuccess("Deletion successful"); displayPubList(store); }; req.onerror = function (evt) { console.error("deletePublication:", evt.target.errorCode); }; }; req.onerror = function (evt) { console.error("deletePublication:", evt.target.errorCode); }; } function displayActionSuccess(msg) { msg = typeof msg != "undefined" ? "Success: " + msg : "Success"; $("#msg").html('<span class="action-success">' + msg + "</span>"); } function displayActionFailure(msg) { msg = typeof msg != "undefined" ? "Failure: " + msg : "Failure"; $("#msg").html('<span class="action-failure">' + msg + "</span>"); } function resetActionStatus() { console.log("resetActionStatus ..."); $("#msg").empty(); console.log("resetActionStatus DONE"); } function addEventListeners() { console.log("addEventListeners"); $("#register-form-reset").click(function (evt) { resetActionStatus(); }); $("#add-button").click(function (evt) { console.log("add ..."); var title = $("#pub-title").val(); var biblioid = $("#pub-biblioid").val(); if (!title || !biblioid) { displayActionFailure("Required field(s) missing"); return; } var year = $("#pub-year").val(); if (year != "") { // Better use Number.isInteger if the engine has EcmaScript 6 if (isNaN(year)) { displayActionFailure("Invalid year"); return; } year = Number(year); } else { year = null; } var file_input = $("#pub-file"); var selected_file = file_input.get(0).files[0]; console.log("selected\_file:", selected_file); // Keeping a reference on how to reset the file input in the UI once we // have its value, but instead of doing that we rather use a "reset" type // input in the HTML form. //file\_input.val(null); var file_url = $("#pub-file-url").val(); if (selected_file) { addPublication(biblioid, title, year, selected_file); } else if (file_url) { addPublicationFromUrl(biblioid, title, year, file_url); } else { addPublication(biblioid, title, year); } }); $("#delete-button").click(function (evt) { console.log("delete ..."); var biblioid = $("#pub-biblioid-to-delete").val(); var key = $("#key-to-delete").val(); if (biblioid != "") { deletePublicationFromBib(biblioid); } else if (key != "") { // Better use Number.isInteger if the engine has EcmaScript 6 if (key == "" || isNaN(key)) { displayActionFailure("Invalid key"); return; } key = Number(key); deletePublication(key); } }); $("#clear-store-button").click(function (evt) { clearObjectStore(); }); var search_button = $("#search-list-button"); search_button.click(function (evt) { displayPubList(); }); } openDb(); addEventListeners(); })(); // Immediately-Invoked Function Expression (IIFE) ``` 線上範例下一步 --- 請參考IndexedDB 文件,看看有甚麼 IndexedDB API 可供使用,實際試玩一下吧。 延伸閱讀 ---- 參照 * IndexedDB API Reference * Indexed Database API Specification * Using IndexedDB in chrome 相關教學 * A simple TODO list using HTML5 IndexedDB. **備註:** 請注意此教學範例用到的已經廢棄的`setVersion()`方法。 * Databinding UI Elements with IndexedDB 相關文章 * IndexedDB — The Store in Your Browser Firefox * Mozilla interface files
GainNode.gain - Web APIs
GainNode.gain ============= `GainNode` 介面的 `gain` 屬性是 a-rate (en-US) `AudioParam` (en-US),代表增益的數值。 語法 -- ```js var audioCtx = new AudioContext(); var gainNode = audioCtx.createGain(); gainNode.gain.value = 0.5; ``` ### 傳回值 一個 `AudioParam` (en-US). **備註:** 雖然傳回的 `AudioParam` 是唯讀的,但是它所代表的值可以更改。 範例 -- See `BaseAudioContext.createGain()` (en-US) for example code showing how to use an `AudioContext` to create a `GainNode`, which is then used to mute and unmute the audio by changing the gain property value. 規格 -- | Specification | | --- | | Web Audio API # dom-gainnode-gain | 瀏覽器相容度 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * Using the Web Audio API (en-US)
Position.timestamp - Web APIs
Position.timestamp ================== **`Position.timestamp`** 是一個唯讀的 `DOMTimeStamp` (en-US) 物件, 此物件代表建立 `Position` 物件的日期和時間,精確度為毫秒。 語法 -- ``` coord = position.timestamp ``` 規格 -- | Specification | | --- | | Geolocation API # timestamp-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Position`。
Position.coords - Web APIs
Position.coords =============== **`Position.coords`** 是一個 `Coordinates` 物件的唯讀屬性,表示地理的特性:回傳的物件中包括位置、地球經緯度、海拔高度和速度,同時也包含著這些值的精準度訊息。 語法 -- ``` coord = position.coords ``` 規格 -- | Specification | | --- | | Geolocation API # coords-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Position`。
Node.removeChild() - Web APIs
Node.removeChild() ================== **`Node.removeChild()`** 方法從 DOM 移除一個子節點,並傳回移除的節點。 語法 -- ``` var oldChild = node.removeChild(child); 或 node.removeChild(child); ``` * `child` 是 DOM 中想要移除的子節點。 * `node` 是 `child` 的父節點。 * `oldChild` 為將被移除的子節點參照,例如:`oldChild === child`. 被刪除的子節點仍然存於記憶體之中,只是不在 DOM 了。從上述的第一種語法形式中,我們知道,透過引用 `oldChild` 還是可以在程式中重新使用已經被移除的子節點。 而第二種語法形式,因為沒有保留 `oldChild` 引用,因此假設你並沒有在其他地方保留節點引用,則它會立即無法使用且不可挽回,而且通常會在短時間內從內存管理中被自動刪除。 如果 `child` 並非某 `element` 節點的子元素,則此方法會拋出異常。而如果調用此方法時,`child` 雖是某 `element` 的子元素,但在嘗試刪除它的過程中已被其他事件處理程序刪除,也會拋出異常(例如 `blur` (en-US))。 ### 會丟出的錯誤 兩種不同的方式拋出異常: 1. 如果 `child` 確實是 `element` 的子元素且確實存在於 DOM,但已被刪除,則會丟出以下異常: `Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node`. 2. 如果 `child` 不存在於頁面的 DOM,則會拋出下列的異常: `Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.` 例子 -- ### 簡單的例子 HTML: ```html <div id="top"> <div id="nested"></div> </div> ``` 在知道父節點的情況下,刪除特定元素: ```js let d = document.getElementById("top"); let d_nested = document.getElementById("nested"); let throwawayNode = d.removeChild(d_nested); ``` 沒有指定父節點的情況下,刪除特定元素: ```js let node = document.getElementById("nested"); if (node.parentNode) { node.parentNode.removeChild(node); } ``` 從一個元素中移除所有子元素: ```js let element = document.getElementById("top"); while (element.firstChild) { element.removeChild(element.firstChild); } ``` ### 造成一個 TypeError ```html <!--Sample HTML code--> <div id="top"></div> <script type="text/javascript"> let top = document.getElementById("top"); let nested = document.getElementById("nested"); // Throws Uncaught TypeError let garbage = top.removeChild(nested); </script> ``` ### 造成一個 NotFoundError ```html <!--Sample HTML code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top = document.getElementById("top"); let nested = document.getElementById("nested"); // This first call correctly removes the node let garbage = top.removeChild(nested); // Throws Uncaught NotFoundError garbage = top.removeChild(nested); </script> ``` 規範 -- * DOM Level 1 Core: removeChild * DOM Level 2 Core: removeChild * DOM Level 3 Core: removeChild 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關連結 ---- * `Node.replaceChild` (en-US) * `Node.parentNode` (en-US) * `ChildNode.remove` (en-US)
Coordinates.longitude - Web APIs
Coordinates.longitude ===================== **`Coordinates.longitude`** 是個唯讀十進位的複數用來代表裝置經度的位置。 語法 -- ``` lon = coordinates.longitude ``` 規格 -- | Specification | | --- | | Geolocation API # latitude-longitude-and-accuracy-attributes | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於`Coordinates` 介面。
Coordinates.speed - Web APIs
Coordinates.speed ================= **`Coordinates.speed`** 回傳唯讀的正複數代表速度,單位為公尺/秒。 如果裝置無法測量這個值則回傳 null。 語法 -- ``` speed = coordinates.speed ``` 規格 -- | Specification | | --- | | Geolocation API # speed-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Coordinates.latitude - Web APIs
Coordinates.latitude ==================== **`Coordinates.latitude`** 是個唯讀十進位的複數用來代表裝置緯度的位置。 語法 -- ``` lat = coordinates.latitude ``` 規格 -- | Specification | | --- | | Geolocation API # latitude-longitude-and-accuracy-attributes | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Coordinates.altitudeAccuracy - Web APIs
Coordinates.altitudeAccuracy ============================ **`Coordinates.altitudeAccuracy`** 是個唯讀的正複數用來代表高度的精準度,單位為公尺,並有 95% 可靠度。如果裝置無法提供這個值則回傳 null。 語法 -- ``` altAcc = coordinates.altitudeAccuracy ``` 規格 -- | Specification | | --- | | Geolocation API # altitude-and-altitudeaccuracy-attributes | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Coordinates.heading - Web APIs
Coordinates.heading =================== **`Coordinates.heading`** 是個唯讀的正複數用來代表裝置前進的方向。這個數值代表你偏離北方多少度,0 度代表你向著正北方,照著順時針的方向遞增(90 度代表正東方,270 度代表正西方)。如果`Coordinates.speed` 為 0 度,則此值為 `NaN` (en-US)。如果這個裝置無法提供這個值則回傳 null。 語法 -- ``` heading = coordinates.heading ``` 規格 -- | Specification | | --- | | Geolocation API # heading-attribute | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Coordinates.altitude - Web APIs
Coordinates.altitude ==================== **`Coordinates.altitude`** 是個唯讀的正複數用來代表距離海平面的高度,單位為公尺。如果無法提供這個值則回傳 null。 語法 -- ``` alt = coordinates.altitude ``` 規格 -- | Specification | | --- | | Geolocation API # altitude-and-altitudeaccuracy-attributes | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Coordinates.accuracy - Web APIs
Coordinates.accuracy ==================== **`Coordinates.accuracy`** 是個唯讀的正複數用來代表 `Coordinates.latitude` 和 `Coordinates.longitude` 的準確度,單位為公尺,並有 95% 可靠度。 語法 -- ``` acc = coordinates.accuracy ``` 規格 -- | Specification | | --- | | Geolocation API # latitude-longitude-and-accuracy-attributes | 瀏覽器的相容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US) * 屬於 `Coordinates` 介面。
Blob.size - Web APIs
Blob.size ========= **`Blob.size`** 屬性回傳以 byte 為單位的 `Blob` 或一個 `File` 的大小。 語法 -- ``` var sizeInBytes = blob.size ``` 值 - 一個數字。 範例 -- ```js // fileInput 是個 HTMLInputElement: <input type="file" multiple id="myfileinput"> var fileInput = document.getElementById("myfileinput"); // files 是個 FileList 物件 (類似 NodeList) var files = fileInput.files; for (var i = 0; i < files.length; i++) { console.log(files[i].name + " has a size of " + files[i].size + " Bytes"); } ``` 規格 -- | Specification | | --- | | File API # dfn-size | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Blob`
Blob() - Web APIs
Blob() ====== **`Blob()`** 建構式會回傳一個新建立的 `Blob` 物件。新物件的內容是由 *array* 參數的成員值串連所構成。 語法 -- ``` var aBlob = new Blob( array, options ); ``` ### 參數 * *array* 可以是一個由 `ArrayBuffer`、`ArrayBufferView` (en-US)、`Blob` 或 `DOMString` 組成的 `Array` 物件,或是上述多種型別物件的混合陣列。這個陣列將會被放進新建立的 `Blob` 物件當中。DOMStrings 的編碼為 UTF-8。 * *options* 是選擇性的 `BlobPropertyBag` 字典物件,有以下兩個指定的屬性: + `type` 屬性,預設值為空字串 `""`,表示將被放進 `Blob` 物件的陣列內容之 MIME 類型。 + `endings` 屬性,表示包含 `\n` 換行字元的字串要如何輸出,預設值為字串 `"transparent"`。此屬性值可為:`"native"`,代表換行字元會被轉為目前作業系統的換行字元編碼。也可以是 `"transparent"`,代表保留 `Blob` 物件中資料的換行字元。 非標準 範例 -- ```js var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single DOMString var oMyBlob = new Blob(aFileParts, { type: "text/html" }); // the blob ``` 規範 -- | Specification | | --- | | File API # constructorBlob | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 廢棄的 `BlobBuilder` (en-US) 和取代他的建構子。
Blob.type - Web APIs
Blob.type ========= `Blob` 物件的 **`type`** 屬性提供檔案的 MIME 類別 (en-US)。若無法辨明型別則回傳空字串。 語法 -- ``` var mimetype = instanceOfFile.type ``` 值 - 一個字串。 範例 -- ```js var i, fileInput, files, allowedFileTypes; // fileInput 是個 HTMLInputElement: <input type="file" multiple id="myfileinput"> fileInput = document.getElementById("myfileinput"); // files 是個 FileList 物件 (類似 NodeList) files = fileInput.files; // 這範例接受 \*.png, \*.jpeg 和 \*.gif 圖片。 allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; for (i = 0; i < files.length; i++) { // 測試 file.type 是否是允許的類別。 if (allowedFileTypes.indexOf(files[i].type) > -1) { // 若符合則執行這裡的程式碼。 } }); ``` 規格 -- | Specification | | --- | | File API # dfn-type | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Blob`
GlobalEventHandlers.onclose - Web APIs
GlobalEventHandlers.onclose =========================== Baseline 2022 ------------- Newly availableSince March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers. * Learn more * See full compatibility * Report feedback 送至視窗的 close event 的處理器(handler)。(不支援 Firefox 2 及 Safari) 語法 -- ``` window.onclose = funcRef; ``` ### 參數 * `funcRef` 為函式的參照。 範例 -- ```js window.onclose = resetThatServerThing; ``` 規範 -- | Specification | | --- | | HTML Standard # event-close | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
submit - Web APIs
submit ====== `submit` 事件會在表單送出時觸發。 要注意的是,`submit` 事件**只會**在 form element (en-US) 上觸發, button (en-US) 或是 submit input (en-US) 則不會觸發。(送出的是「表單」,而非「按鈕」) 基本資料 ---- 定義規範 HTML5 Interface `Event` Bubbles 是 雖說在規範上這是個不 bubble 的事件 Cancelable 是 Target Element 默認行動 修改(傳送表單內容至伺服器)。 屬性 -- | Property | Type | Description | | --- | --- | --- | | `target` Read only | `EventTarget` | The event target (the topmost target in the DOM tree). | | `type` Read only | `DOMString` | The type of event. | | `bubbles` Read only | `Boolean` | Whether the event normally bubbles or not. | | `cancelable` Read only | `Boolean` | Whether the event is cancellable or not. | 規範 -- | Specification | | --- | | HTML Standard # event-submit | | HTML Standard # handler-onsubmit |
Navigator.language - Web APIs
Navigator.language ================== **`Navigator.language`** 是一個唯讀的屬性,回傳使用者偏好的語言字串,通常是瀏覽器 UI 的文字 語法 -- ```js const lang = navigator.language ``` ### 值 一個 `DOMString`. `lang` 儲存一個代表此語言的字串。定義在BCP 47。範例: 合法的語言代碼 "en", "en-US", "fr", "fr-FR", "es-ES", etc. 在 iOS 小於 10.2 的 Safari 國碼是回傳小寫的喲! "en-us", "fr-fr" etc. 範例 -- ```js if (/^en\b/.test(navigator.language)) { doLangSelect(window.navigator.language); } ``` 規格 -- | Specification | | --- | | HTML Standard # dom-navigator-language-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Navigator.languages` (en-US) * `navigator` (en-US)
Navigator.geolocation - Web APIs
Navigator.geolocation ===================== **`Navigator.geolocation`** 回傳一個唯讀的 `Geolocation` 物件,透過這個物件可以存取設備的位置訊息。同時也允許網站或應用程式根據使用者的位置提供客製化的結果。 **備註:** 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。 語法 -- ``` geo = navigator.geolocation ``` 規格 -- | Specification | | --- | | Geolocation API # dom-navigator-geolocation | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 請參考 --- * Using geolocation (en-US)
Firefox 3 Web-based protocol handler - Web APIs
Firefox 3 Web-based protocol handler ==================================== ### 摘要 window.navigator.registerProtocolHandler 讓網站可以將自己註冊為特定通訊協定的處理者。 ### 語法 ``` window.navigator.registerProtocolHandler(protocol, uri, title); ``` * protocol 是網站想要處理的 protocol 名稱,用字串表示。 * uri 是要給 handler 處理的 URI 字串。你可以在字串裡用 "%s" 來代表 escaped 過、需要處理的 URI。 * title 是 handler 的 title,會以字串的形式呈現給使用者。 ### 例子 ``` navigator.registerProtocolHandler("mailto", "https://mail.google.com/mail?view=cm&tf=0&to=%s", "Google Mail"); ``` 這會建立一個 handler,它允許 mailto 的鏈結將使用者帶到 Google Mail,將鏈結中指定的 email 位址插入到 URL。 ### 參考資料 1. DOM:window.navigator.registerProtocolHandler 原始網頁 ### 延伸閱讀 1. WHATWG's Web Applications 1.0 working draft
File.File() - Web APIs
File.File() =========== **`File()`** 建構子建立一個新的 `File` 物件實例 語法 -- ``` var myFile = new File(bits, name[, options]); ``` ### 參數 *bits* An `Array` of `ArrayBuffer`, `ArrayBufferView` (en-US), `Blob`, or `DOMString` objects — 或是由這些物件組成的集合。這是以 UTF-8 編碼的檔案內容。 *name* 檔案名稱或檔案的路徑(`USVString` (en-US))。 *options* 選擇性 物件選項,包含物件非必要的屬性,以下為可得到的屬性: * `type`: 物件的 MIME 類型(`DOMString` )將被放進檔案中,預設為 ""(空值)。 * `lastModified`: 檔案最後修改時間,格式為毫秒,預設為 `Date.now()`. 範例 -- ```js var file = new File(["foo"], "foo.txt", { type: "text/plain", }); ``` 規格 -- | Specification | | --- | | File API # file-constructor | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 看更多 --- * `FileReader` * `Blob`
File.fileName - Web APIs
File.fileName ============= **非標準:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. **gecko 7.0:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 總覽 -- 回傳檔案名稱,基於安全因素,檔案路徑不包含這個屬性。 **備註:** 這個檔案是廢棄的,使用 `File.name` 取代。 語法 -- ```js var name = instanceOfFile.fileName; ``` 數值 -- 字串 格式 -- 尚無資料 看更多 --- * `File.name`
HTMLSelectElement.setCustomValidity() - Web APIs
HTMLSelectElement.setCustomValidity() ===================================== Baseline 2023 ------------- Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers. * Learn more * See full compatibility * Report feedback **`HTMLSelectElement.setCustomValidity()`** 方法可為指定的元素設定自定義檢核訊息。使用空字串表示元素*沒有*發生違反自定檢核條件的錯誤。 語法 -- ```js selectElt.setCustomValidity(string); ``` ### 參數 * *string* 為 `DOMString`,代表錯誤訊息。 規範 -- | Specification | | --- | | HTML Standard # dom-cva-setcustomvalidity-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 表單驗證 (en-US)
HTMLSelectElement.checkValidity() - Web APIs
HTMLSelectElement.checkValidity() ================================= Baseline 2023 ------------- Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers. * Learn more * See full compatibility * Report feedback **`HTMLSelectElement.checkValidity()`** 方法會檢查元素是否有任何的檢核、驗證條件,並且檢查是否滿足這些條件。如果元素沒有通過這些檢核,瀏覽器會於該元素上觸發一個可取消的 `invalid` (en-US) 事件,並回傳 `false`。 語法 -- ```js var result = selectElt.checkValidity(); ``` 規範 -- | Specification | | --- | | HTML Standard # dom-cva-checkvalidity-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * Form validation. (en-US)
Document.registerElement() - Web APIs
Document.registerElement() ========================== Limited availability -------------------- This feature is not Baseline because it does not work in some of the most widely-used browsers. * Learn more * See full compatibility * Report feedback **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 **警告:** document.registerElement() 已經被棄用,建議使用 customElements.define(). **`document.registerElement()`** 可以在瀏覽器中註冊一個新的自訂標籤(元素)and returns a constructor for the new element. **備註:** This is an experimental technology. The browser you use it in must support Web Components. See Enabling Web Components in Firefox (en-US). 語法 -- ``` var constructor = document.registerElement(tag-name, options); ``` ### 參數 *標籤名稱* 自訂的標籤名稱需有一個 橫線 ( - ), 例如`my-tag`. *options 選擇性* An object with properties **prototype** to base the custom element on, and **extends**, an existing tag to extend. Both of these are optional. 例子 -- 這是一個非常簡單的例子: ```js var Mytag = document.registerElement("my-tag"); ``` 現在新的標籤已經在瀏覽器中註冊了. The `Mytag` variable holds a constructor that you can use to create a `my-tag` element in the document as follows: ```js document.body.appendChild(new Mytag()); ``` This inserts an empty `my-tag` element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. Here is one way to add content to the new tag: ```js var mytag = document.getElementsByTagName("my-tag")[0]; mytag.textContent = "I am a my-tag element."; ``` 瀏覽器支援性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 也看一下 ---- * Custom Elements (en-US)
使用 Web Notifications - Web APIs
使用 Web Notifications ==================== **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 摘要 -- Web Notifications API 可將通知傳送至頁面以外的系統層級並顯示通知。因此即使 Web Apps 處於閒置狀態,亦可傳送資訊予使用者。絕佳範例之一,就是在使用其他 Apps 時,Web Mail App 同樣可通知使用者已接收到新郵件。 要求權限 ---- ### 網頁內容 在 Apps 傳送通知之前,使用者必須先許可 Apps 的動作。只要 APIs 嘗試予網頁之外的東西互動,均必須先獲得使用者的授權。如此可避免濫發通知而影響使用經驗。 透過 `Notification.permission` (en-US) 唯讀屬性,要傳送通知的 Apps 將檢查目前的授權狀態。此屬性共有 3 組參數: * `default`:使用者尚未給予任何權限 (因此不會顯示任何通知) * `granted`:使用者允許接收到 Apps 的通知 * `denied`:使用者拒絕接收 Apps 的通知 **備註:** Chrome 與 Safari 尚未建構 `permission` 屬性。 若使用者尚未給予權限,則 Apps 必須透過 `Notification.requestPermission()` (en-US) 函式讓使用者選擇,接著由此函式接收 1 組回呼 (Callback) 函式作為參數;而該回呼函式則提供使用者是否授權的資訊。 以下為啟動 Apps 時要求權限的常用範例: ```js window.addEventListener("load", function () { Notification.requestPermission(function (status) { // This allows to use Notification.permission with Chrome/Safari if (Notification.permission !== status) { Notification.permission = status; } }); }); ``` **備註:** Chrome 不允許於載入事件中呼叫 `Notification.requestPermission()` (en-US) (參閱 issue 274284)。 ### 已安裝的 Apps 在安裝 Apps 之後,若於 Apps 的 manifest 檔案中直接添加權限,即可省去再次向使用者要求權限的動作。 ```json permissions: { "desktop-notification": { "description: "Allows to display notifications on the user's desktop. } } ``` 建立通知 ---- 透過 `Notification` 建構子 (Constructor) 即可建立通知。此建構子包含 1 組標題,可於通知內顯示;另有如 `icon` (en-US) 或文字 `body` (en-US) 等數個選項,可強化通知的內容。 在建立實體 (Instantiated) 之後,就會儘快顯示通知。若要追蹤通知的目前狀態,必須在 `Notification` 的實體階層觸發 4 個事件: * show:對使用者顯示通知之後,隨即觸發 * click (en-US):使用者點擊通知之後,隨即觸發 * close:關閉通知之後,隨即觸發 * error (en-US):通知發生任何錯誤 (大多數是因為某種情況而未顯示通知),隨即觸發 而透過 `onshow` (en-US)、`onclick` (en-US)、`onclose` (en-US),或 `onerror` (en-US) 等事件處理器 (Event handler),即可追蹤這些事件。由於 `Notification` 是繼承 `EventTarget` 而來,因此亦可使用 `addEventListener()` (en-US) 函式。 **備註:** Firefox 與 Safari 並未遵守 close 事件的規格。此規格雖然規定「僅限使用者能關閉通知」,但 Firefox 與 Safari 卻可於數分鐘後自動關閉通知。因此不一定是由使用者關閉通知。此規格並明確規定「應透過 `Notification.close()` (en-US) 函式,於應用程式層級完成自動關閉通知」。範例程式碼如下: ```js var n = new Notification("Hi!"); n.onshow = function () { setTimeout(n.close, 5000); }; ``` ### 簡易範例 先假設下列基本 HTML: ```html <button>Notify me!</button> ``` 則能以這種方法處理通知: ```js window.addEventListener("load", function () { // At first, let's check if we have permission for notification // If not, let's ask for it if (Notification && Notification.permission !== "granted") { Notification.requestPermission(function (status) { if (Notification.permission !== status) { Notification.permission = status; } }); } var button = document.getElementsByTagName("button")[0]; button.addEventListener("click", function () { // If the user agreed to get notified if (Notification && Notification.permission === "granted") { var n = new Notification("Hi!"); } // If the user hasn't told if he wants to be notified or not // Note: because of Chrome, we are not sure the permission property // is set, therefore it's unsafe to check for the "default" value. else if (Notification && Notification.permission !== "denied") { Notification.requestPermission(function (status) { if (Notification.permission !== status) { Notification.permission = status; } // If the user said okay if (status === "granted") { var n = new Notification("Hi!"); } // Otherwise, we can fallback to a regular modal alert else { alert("Hi!"); } }); } // If the user refuses to get notified else { // We can fallback to a regular modal alert alert("Hi!"); } }); }); ``` ### 現場測試結果 若無法顯示,可至本文右上角「Language」切換回英文原文觀看。 處理多筆通知 ------ 某些情況下 (如某個即時訊息 App 持續通知每一筆進來的訊息),使用者可能會接收大量的通知。為了避免太多非必要訊息擠爆使用者的桌面,則應該讓等待中的通知進入佇列。 將標籤添加至任何新的通知,即可達到佇列效果。若通知擁有相同的標籤且尚未顯示,則新通知就會取代先前的通知;反之,若已顯示了相同標籤的通知,就會關閉先前的通知而顯示新通知。 ### 標籤範例 先假設下列基本 HTML: ```html <button>Notify me!</button> ``` 則能以下列方式處理多筆通知: ```js window.addEventListener('load', function () { // At first, let's check if we have permission for notification // If not, let's ask for it if (Notification && Notification.permission !== "granted") { Notification.requestPermission(function (status) { if (Notification.permission !== status) { Notification.permission = status; } }); } var button = document.getElementsByTagName('button')[0]; button.addEventListener('click', function () { // If the user agreed to get notified // Let's try to send ten notifications if (Notification && Notification.permission === "granted") { for (var i = 0; i < 10; i++) { // Thanks to the tag, we should only see the "Hi! 10" notification var n = new Notification("Hi! " + i, {tag: 'soManyNotification'}); } } // If the user hasn't told if he wants to be notified or not // Note: because of Chrome, we are not sure the permission property // is set, therefore it's unsafe to check for the "default" value. else if (Notification && Notification.permission !== "denied") { Notification.requestPermission(function (status) { if (Notification.permission !== status) { Notification.permission = status; } // If the user said okay if (status === "granted") { for (var i = 0; i < 10; i++) { // Thanks to the tag, we should only see the "Hi! 10" notification var n = new Notification("Hi! " + i, {tag: 'soManyNotification'}); } } // Otherwise, we can fallback to a regular modal alert else { alert(Hi!"); } }); } // If the user refuses to get notified else { // We can fallback to a regular modal alert alert(Hi!"); } }); }); ``` #### 現場測試結果 若無法顯示,可至本文右上角「Language」切換回英文原文觀看。 規格 -- | Specification | | --- | | Notifications API Standard # api | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 另可參閱 ---- * `Notification`
使用 XMLHttpRequest - Web APIs
使用 XMLHttpRequest ================= 要送出一個 HTTP 請求,需要建立一個 `XMLHttpRequest` 物件、開啟一個 URL,並發起一個請求。在交易(transaction)完成後,`XMLHttpRequest` 物件將會包含如回應內容(response body)及 HTTP 狀態等等請求結果中的有用資訊。本頁概述了一些常見的、甚至略為難理解的 `XMLHttpRequest` 物件使用案例。 ```js function reqListener() { console.log(this.responseText); } var oReq = new XMLHttpRequest(); oReq.addEventListener("load", reqListener); oReq.open("GET", "http://www.example.org/example.txt"); oReq.send(); ``` 請求類型 ---- 透過 `XMLHttpRequest` 建立的請求,其取得資料的方式可以為非同步(asynchronously)或同步(synchronously)兩種之一。請求的種類是由 `XMLHttpRequest.open()` (en-US) 方法的選擇性參數 `async`(第三個參數)決定。若 `async` 參數為 `true` 或是未指定,`XMLHttpRequest` 會被設定為非同步,相反的若為 `false` 則會被設定為同步。這兩種請求類型的細節討論與示範可以在同步與非同步請求頁面中找到。一般來說,很少會使用到同步請求。 **備註:** 自 Gecko 30.0 開始,在主執行緒上的同步請求因其差勁的使用者體驗已被棄用。 處理回應 ---- `XMLHttpRequest` 的活動標準規範(living standard specification)定義了數個 `XMLHttpRequest` 建構出之物件的回應屬性。這些回應屬性告訴客戶端關於 `XMLHttpRequest` 回應狀態的重要資訊。一些處理非文字類型回應的案例可能會需要一些在下面小節所說明的分析和操作。 ### 分析及操作 `responseXML` 屬性 透過 `XMLHttpRequest` 取得一個遠端的 XML 文件內容時,`responseXML` 屬性(property)將會是一個由 XML 文件解析而來的 DOM 物件。這可能會造成分析和操作上的一些困難,以下有四種主要的 XML 文件分析方式: 1. 利用 XPath 指向需要部份。 2. 手動的解析與序列化 XML 成字串或物件。 3. 利用 `XMLSerializer` (en-US) 來序列化 **DOM 樹成字串或檔案**。 4. 如果事先知道 XML 文件內容,可利用 `RegExp` (en-US)。如果換行符號會影響 `RegExp` 掃描結果,則需要移除換行符號。然而,這項方式應該是「最後不得已的手段(last resort)」,因為一旦 XML 文件內容稍有變動,此方式就可能會失敗。 ### 分析及操作含有 HTML 文件的 `responseText` 屬性 **備註:** W3C 的XMLHttpRequest 規範允許透過 `XMLHttpRequest.responseXML` 屬性(property)來解析 HTML。相關細節請參考 HTML in XMLHttpRequest 一文。 若透過 `XMLHttpRequest` 來取得一個遠端的 HTML 網頁內容,則 `responseText` 屬性(property)會是「一串(soup)」包含所有 HTML 標籤的字串。這可能使得在分析和操作上造成困難,以下有三種主要分析此一大串 HTML 字串的方式: 1. 利用 `XMLHttpRequest.responseXML` 屬性。 2. 將內容透過 `fragment.body.innerHTML` 注入文件片段(document fragment)之 `body` 中,並遍歷(traverse)文件片段的 DOM。 3. 如果事先知道 HTML 之 `responseText` 內容,可利用 `RegExp` (en-US)。如果換行符號會影響 `RegExp` 掃描結果,則需要移除換行符號。然而,這項方式應該是「最後不得已的手段(last resort)」,因為一旦 HTML 程式碼稍有變動,此方式就可能會失敗。 處理二進位資料 ------- 僅管 `XMLHttpRequest` 最常被用在傳送及接收文字資料,但它其實也可以傳送及接收二進位內容。有幾種經過良好測試的方法可以用來強制使用 `XMLHttpRequest` 發送二進位資料。透過使用 `XMLHttpRequest` 物件的 `.overrideMimeType()` 方法是一個可行的解決方案。 ```js var oReq = new XMLHttpRequest(); oReq.open("GET", url); // retrieve data unprocessed as a binary string oReq.overrideMimeType("text/plain; charset=x-user-defined"); /\* ... \*/ ``` XMLHttpRequest Level 2 規範加入了新的 `responseType` 屬性,讓收發二進位資料變得容易許多。 ```js var oReq = new XMLHttpRequest(); oReq.onload = function (e) { var arraybuffer = oReq.response; // not responseText /\* ... \*/ }; oReq.open("GET", url); oReq.responseType = "arraybuffer"; oReq.send(); ``` 更多的範例可參考傳送及接收二進位資料頁面。 監視進度 ---- `XMLHttpRequest` 提供了監聽請求於處理過程中所發生的各項事件之能力。包括了定期進度通知、錯誤通知等等。 `XMLHttpRequest` 支援可監視其傳輸進度的 DOM 進度事件,此事件遵循進度事件規範:這些事件實作了 `ProgressEvent` (en-US) 介面。 ```js var oReq = new XMLHttpRequest(); oReq.addEventListener("progress", updateProgress); oReq.addEventListener("load", transferComplete); oReq.addEventListener("error", transferFailed); oReq.addEventListener("abort", transferCanceled); oReq.open(); // ... // progress on transfers from the server to the client (downloads) function updateProgress(oEvent) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total; // ... } else { // Unable to compute progress information since the total size is unknown } } function transferComplete(evt) { console.log("The transfer is complete."); } function transferFailed(evt) { console.log("An error occurred while transferring the file."); } function transferCanceled(evt) { console.log("The transfer has been canceled by the user."); } ``` 第 3-6 行加入了事件監聽器來處理使用 `XMLHttpRequest` 執行資料收發過程中的各類事件。 **備註:** 必須在呼叫 `open()` 方法開啟請求連線之前就註冊好事件監聽器,否則 `progress` 事件將不會被觸發。 在這個例子中,指定了 `updateProgress()` 函式作為 `progress` 事件處理器,`progress` 事件處理器會於 `progress` 事件物件的 `total` 及 `loaded` 屬性分別接收到要傳輸的總位元數及已送出的位元數。然而,假如 `lengthComputable` 屬性值為假,則代表要傳輸的總位元數是未知且 `total` 屬性值將會為零。 `progress` 事件同時存在於上傳及下載傳輸中。下載的相關事件會於 `XMLHttpRequest` 物件自己身上被觸發,如上面的範例。而上傳相關事件則在 `XMLHttpRequest.upload` 物件上被觸發,如以下範例: ```js var oReq = new XMLHttpRequest(); oReq.upload.addEventListener("progress", updateProgress); oReq.upload.addEventListener("load", transferComplete); oReq.upload.addEventListener("error", transferFailed); oReq.upload.addEventListener("abort", transferCanceled); oReq.open(); ``` **備註:** `progress` 事件無法用於 `file:` 通訊協定。 **備註:** 自 Gecko 9.0 開始,接收到每一個資料的區塊(chunk)時,`progress` 事件都會被觸發。包括在 `progress` 事件被觸發前,就已經接收到含有最後一個資料區塊的最後一個封包並且關閉連線的狀況下,在載入此封包時仍會自動觸發 `progress` 事件。這代表我們可以僅關注 `progress` 事件即能夠可靠的監視進度。 **備註:** 在 Gecko 12.0 中,如果 `XMLHttpRequest` 的 `responseType` 屬性為「moz-blob」,那麼 `progress` 事件觸發時的 `XMLHttpRequest.response` 值會是一個目前包含了所接收資料的 `Blob`。 我們也可以透過 `loadend` 事件來偵測到所有之三種下載結束狀況(`abort`、`load` 或 `error`): ```js req.addEventListener("loadend", loadEnd); function loadEnd(e) { console.log( "The transfer finished (although we don't know if it succeeded or not).", ); } ``` 請注意由 `loadend` 事件中接收到的資訊並無法確定是由何種結束狀況所觸發。不過還是可以用 `loadend` 事件來處理所有傳輸結束情況下需要執行的任務。 提交表單與上傳檔案 --------- `XMLHttpRequest` 物件實體有兩種方式來提交表單: * 僅使用 AJAX * 使用 `FormData` API 使用 `FormData` API 是最簡單、快速的方式,但不利於將資料集合進行字串化。 只使用 AJAX 的方式較為複雜,但也更加靈活、強大。 ### 僅使用 `XMLHttpRequest` 以不透過 `FormData` API 提交表單的方式在大多數的情況下都不需要使用其他額外的 API。唯一的例外是**要上傳一或多個檔案**時,會需要用到 `FileReader` API。 #### 提交方法簡介 一個 HTML 表單(form) (en-US)有以下四種提交方式: * 使用 `POST` 方法,並且設定 `enctype` 屬性(attribute)為 `application/x-www-form-urlencoded`(預設值)。 * 使用 `POST` 方法,並且設定 `enctype` 屬性為 `text/plain`。 * 使用 `POST` 方法,並且設定 `enctype` 屬性為 `multipart/form-data`。 * 使用 `GET` 方法(在此情況下,`enctype` 屬性將會被忽略)。 現在,假設要提交一個只包含兩個欄位的表單,欄位名稱為 `foo` 及 `baz`。若是使用 `POST` 方法,伺服器將會收到一個如以下三個例子之一的字串,這取決於所使用的編碼類型(encoding type): * 方法:`POST`;編碼類型:`application/x-www-form-urlencoded`(預設值): ``` Content-Type: application/x-www-form-urlencoded foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A ``` * 方法:`POST`;編碼類型:`text/plain`: ``` Content-Type: text/plain foo=bar baz=The first line. The second line. ``` * 方法:`POST`;編碼類型:`multipart/form-data`: ``` Content-Type: multipart/form-data; boundary=---------------------------314911788813839 -----------------------------314911788813839 Content-Disposition: form-data; name="foo" bar -----------------------------314911788813839 Content-Disposition: form-data; name="baz" The first line. The second line. -----------------------------314911788813839-- ``` 如果是使用 `GET` 方法,一個如下方的字串會被直接附加入到 URL 上: ``` ?foo=bar&baz=The%20first%20line.%0AThe%20second%20line. ``` #### 小型原生框架 在我們提交 `<form>` (en-US) 時,瀏覽器自動幫我們做了上面這些工作。假如要使用 JavaScript 達到同樣的效果就必須告訴直譯器(interpreter)要處理的*所有事*。然而,如何透過*純粹的* AJAX 來傳送表單複雜到難以在本頁解釋所有細節。基於這個理由,我們改為在這此提供**一組完整(教學用)的框架**,可用於上述四種的每一種*提交*(submit),並包括**上傳檔案**: ``` <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Sending forms with pure AJAX &ndash; MDN</title> <script type="text/javascript"> "use strict"; /\*\ |\*| |\*| :: XMLHttpRequest.prototype.sendAsBinary() Polyfill :: |\*| |\*| https://developer.mozilla.org/zh-TW/docs/DOM/XMLHttpRequest#sendAsBinary() \\*/ if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function (sData) { var nBytes = sData.length, ui8Data = new Uint8Array(nBytes); for (var nIdx = 0; nIdx < nBytes; nIdx++) { ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff; } /\* send as ArrayBufferView...: \*/ this.send(ui8Data); /\* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); \*/ }; } /\*\ |\*| |\*| :: AJAX Form Submit Framework :: |\*| |\*| https://developer.mozilla.org/zh-TW/docs/DOM/XMLHttpRequest\_API/Using\_XMLHttpRequest |\*| |\*| This framework is released under the GNU Public License, version 3 or later. |\*| https://www.gnu.org/licenses/gpl-3.0-standalone.html |\*| |\*| Syntax: |\*| |\*| AJAXSubmit(HTMLFormElement); \\*/ var AJAXSubmit = (function () { function ajaxSuccess() { /\* console.log("AJAXSubmit - Success!"); \*/ console.log(this.responseText); /\* you can get the serialized data through the "submittedData" custom property: \*/ /\* console.log(JSON.stringify(this.submittedData)); \*/ } function submitData(oData) { /\* the AJAX request... \*/ var oAjaxReq = new XMLHttpRequest(); oAjaxReq.submittedData = oData; oAjaxReq.onload = ajaxSuccess; if (oData.technique === 0) { /\* method is GET \*/ oAjaxReq.open( "get", oData.receiver.replace( /(?:\?.\*)?$/, oData.segments.length > 0 ? "?" + oData.segments.join("&") : "", ), true, ); oAjaxReq.send(null); } else { /\* method is POST \*/ oAjaxReq.open("post", oData.receiver, true); if (oData.technique === 3) { /\* enctype is multipart/form-data \*/ var sBoundary = "---------------------------" + Date.now().toString(16); oAjaxReq.setRequestHeader( "Content-Type", "multipart\/form-data; boundary=" + sBoundary, ); oAjaxReq.sendAsBinary( "--" + sBoundary + "\r\n" + oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n", ); } else { /\* enctype is application/x-www-form-urlencoded or text/plain \*/ oAjaxReq.setRequestHeader("Content-Type", oData.contentType); oAjaxReq.send( oData.segments.join(oData.technique === 2 ? "\r\n" : "&"), ); } } } function processStatus(oData) { if (oData.status > 0) { return; } /\* the form is now totally serialized! do something before sending it to the server... \*/ /\* doSomething(oData); \*/ /\* console.log("AJAXSubmit - The form is now serialized. Submitting..."); \*/ submitData(oData); } function pushSegment(oFREvt) { this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n"; this.owner.status--; processStatus(this.owner); } function plainEscape(sText) { /\* How should I treat a text/plain form encoding? What characters are not allowed? this is what I suppose...: \*/ /\* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" \*/ return sText.replace(/[\s\=\\]/g, "\\$&"); } function SubmitRequest(oTarget) { var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post"; /\* console.log("AJAXSubmit - Serializing form..."); \*/ this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded"; this.technique = bIsPost ? this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0; this.receiver = oTarget.action; this.status = 0; this.segments = []; var fFilter = this.technique === 2 ? plainEscape : escape; for (var nItem = 0; nItem < oTarget.elements.length; nItem++) { oField = oTarget.elements[nItem]; if (!oField.hasAttribute("name")) { continue; } sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT"; if (sFieldType === "FILE" && oField.files.length > 0) { if (this.technique === 3) { /\* enctype is multipart/form-data \*/ for (nFile = 0; nFile < oField.files.length; nFile++) { oFile = oField.files[nFile]; oSegmReq = new FileReader(); /\* (custom properties:) \*/ oSegmReq.segmentIdx = this.segments.length; oSegmReq.owner = this; /\* (end of custom properties) \*/ oSegmReq.onload = pushSegment; this.segments.push( 'Content-Disposition: form-data; name="' + oField.name + '"; filename="' + oFile.name + '"\r\nContent-Type: ' + oFile.type + "\r\n\r\n", ); this.status++; oSegmReq.readAsBinaryString(oFile); } } else { /\* enctype is application/x-www-form-urlencoded or text/plain or method is GET: files will not be sent! \*/ for ( nFile = 0; nFile < oField.files.length; this.segments.push( fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name), ) ); } } else if ( (sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked ) { /\* NOTE: this will submit \_all\_ submit buttons. Detecting the correct one is non-trivial. \*/ /\* field type is not FILE or is FILE but is empty \*/ this.segments.push( this.technique === 3 /\* enctype is multipart/form-data \*/ ? 'Content-Disposition: form-data; name="' + oField.name + '"\r\n\r\n' + oField.value + "\r\n" : /\* enctype is application/x-www-form-urlencoded or text/plain or method is GET \*/ fFilter(oField.name) + "=" + fFilter(oField.value), ); } } processStatus(this); } return function (oFormElement) { if (!oFormElement.action) { return; } new SubmitRequest(oFormElement); }; })(); </script> </head> <body> <h1>Sending forms with pure AJAX</h1> <h2>Using the GET method</h2> <form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h2>Using the POST method</h2> <h3>Enctype: application/x-www-form-urlencoded (default)</h3> <form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h3>Enctype: text/plain</h3> <form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p>Your name: <input type="text" name="user" /></p> <p> Your message:<br /> <textarea name="message" cols="40" rows="8"></textarea> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h3>Enctype: multipart/form-data</h3> <form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Upload example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /><br /> Sex: <input id="sex\_male" type="radio" name="sex" value="male" /> <label for="sex\_male">Male</label> <input id="sex\_female" type="radio" name="sex" value="female" /> <label for="sex\_female">Female</label><br /> Password: <input type="password" name="secret" /><br /> What do you prefer: <select name="image\_type"> <option>Books</option> <option>Cinema</option> <option>TV</option> </select> </p> <p> Post your photos: <input type="file" multiple name="photos[]" /> </p> <p> <input id="vehicle\_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle\_bike">I have a bike</label><br /> <input id="vehicle\_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle\_car">I have a car</label> </p> <p> Describe yourself:<br /> <textarea name="description" cols="50" rows="8"></textarea> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> </body> </html> ``` 為了進行測試,建立一個名為 **register.php** 的 PHP 頁面(即為上面範例表單之 `action` 屬性(attribute)所指向的位置),並輸入以下*最簡化*的內容: ```php <?php /\* register.php \*/ header("Content-type: text/plain"); /\* NOTE: You should never use `print\_r()` in production scripts, or otherwise output client-submitted data without sanitizing it first. Failing to sanitize can lead to cross-site scripting vulnerabilities. \*/ echo ":: data received via GET ::\n\n"; print\_r($\_GET); echo "\n\n:: Data received via POST ::\n\n"; print\_r($\_POST); echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n"; if (isset($HTTP\_RAW\_POST\_DATA)) { echo $HTTP\_RAW\_POST\_DATA; } echo "\n\n:: Files received ::\n\n"; print\_r($\_FILES); ``` 使用這個框架的語法簡單如下: ``` AJAXSubmit(myForm); ``` **備註:** 此框架使用了 `FileReader` API 來發送檔案上傳。這是個較新的 API,且 IE9 或其先前版本並未實作。因為這個理由,AJAX-only 上傳被認為是**一項實驗性技術**。若沒有需要上傳二進位檔案,此框架可於大部分瀏覽器中運作良好。 **備註:** 傳送二進位檔案的最佳方式是藉由 `ArrayBuffers` 或 `Blobs` 結合 `send()` (en-US) 方法來送出,如果可以也能搭配 `FileReader` API 的 `readAsArrayBuffer()` (en-US) 方法先進行讀取。但因為這段程式指令碼(script)的目的是要處理可字串化的 (en-US)原始資料,所以使用 `sendAsBinary()` 方法結合 `FileReader` API 的 `readAsBinaryString()` (en-US) 方法。就其本身來看,以上的指令碼只有在處理小型檔案時才有意義。假如不打算上傳二進位內容,請考慮使用 `FormData` API。 **備註:** 非標準的 `sendAsBinary` 方法在 Gecko 31 已被認為是棄用的(deprecated),並且即將被移除。而標準的 `send(Blob data)` 方法可以作為替代。 ### 使用 FormData 物件 `FormData` 建構式可以讓我們收集一連串名/值對資料並透過 `XMLHttpRequest` 送出。其主要用於傳送表單資料,但也能夠單獨的由表單建立來傳輸使用者輸入的資料。若表單的編碼類型(encoding type)被設定為「multipart/form-data」,則由 `FormData` 所發送的資料格式和表單用來傳送資料的 `submit()` 方法相同。FormData 物件可以搭配 `XMLHttpRequest` 以多種方式使用。相關的範例,以及可以怎麼利用 FormData 配合 XMLHttpRequest 的說明,請參考使用 FormData 物件頁面。為了教學使用,下方為**一個利用 `FormData` API 來改寫先前範例的*翻譯*版本**。注意這段精簡後的程式碼: ``` <!doctype html> <html> <head> <meta http-equiv="Content-Type" charset="UTF-8" /> <title>Sending forms with FormData &ndash; MDN</title> <script> "use strict"; function ajaxSuccess() { console.log(this.responseText); } function AJAXSubmit(oFormElement) { if (!oFormElement.action) { return; } var oReq = new XMLHttpRequest(); oReq.onload = ajaxSuccess; if (oFormElement.method.toLowerCase() === "post") { oReq.open("post", oFormElement.action); oReq.send(new FormData(oFormElement)); } else { var oField, sFieldType, nFile, sSearch = ""; for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) { oField = oFormElement.elements[nItem]; if (!oField.hasAttribute("name")) { continue; } sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT"; if (sFieldType === "FILE") { for ( nFile = 0; nFile < oField.files.length; sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name) ); } else if ( (sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked ) { sSearch += "&" + escape(oField.name) + "=" + escape(oField.value); } } oReq.open( "get", oFormElement.action.replace( /(?:\?.\*)?$/, sSearch.replace(/^&/, "?"), ), true, ); oReq.send(null); } } </script> </head> <body> <h1>Sending forms with FormData</h1> <h2>Using the GET method</h2> <form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h2>Using the POST method</h2> <h3>Enctype: application/x-www-form-urlencoded (default)</h3> <form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h3>Enctype: text/plain</h3> <p>The text/plain encoding is not supported by the FormData API.</p> <h3>Enctype: multipart/form-data</h3> <form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Upload example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /><br /> Sex: <input id="sex\_male" type="radio" name="sex" value="male" /> <label for="sex\_male">Male</label> <input id="sex\_female" type="radio" name="sex" value="female" /> <label for="sex\_female">Female</label><br /> Password: <input type="password" name="secret" /><br /> What do you prefer: <select name="image\_type"> <option>Books</option> <option>Cinema</option> <option>TV</option> </select> </p> <p> Post your photos: <input type="file" multiple name="photos[]" /> </p> <p> <input id="vehicle\_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle\_bike">I have a bike</label><br /> <input id="vehicle\_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle\_car">I have a car</label> </p> <p> Describe yourself:<br /> <textarea name="description" cols="50" rows="8"></textarea> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> </body> </html> ``` **備註:** 如同之前所說,**`FormData` 物件是不能被字串化的物件**。若想要字串化一個被提交的資料,請使用先前的*純* AJAX 範例。還要注意的是,雖然在這個例子中有一些 `file` `<input>` (en-US) 欄位,**當你透過 `FormData` API 來提交表單便也不需要使用 `FileReader` API**:檔案會自動地載入並上傳。 取得最後修改日期 -------- ```js function getHeaderTime() { console.log( this.getResponseHeader("Last-Modified"), ); /\* A valid GMTString date or null \*/ } var oReq = new XMLHttpRequest(); oReq.open("HEAD" /\* use HEAD if you only need the headers! \*/, "yourpage.html"); oReq.onload = getHeaderTime; oReq.send(); ``` ### 當最後修改日期改變時做一些事 先建立兩個函式: ```js function getHeaderTime() { var nLastVisit = parseFloat( window.localStorage.getItem("lm\_" + this.filepath), ); var nLastModif = Date.parse(this.getResponseHeader("Last-Modified")); if (isNaN(nLastVisit) || nLastModif > nLastVisit) { window.localStorage.setItem("lm\_" + this.filepath, Date.now()); isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit); } } function ifHasChanged(sURL, fCallback) { var oReq = new XMLHttpRequest(); oReq.open("HEAD" /\* use HEAD - we only need the headers! \*/, sURL); oReq.callback = fCallback; oReq.filepath = sURL; oReq.onload = getHeaderTime; oReq.send(); } ``` 並進行測試: ```js /\* Let's test the file "yourpage.html"... \*/ ifHasChanged("yourpage.html", function (nModif, nVisit) { console.log( "The page '" + this.filepath + "' has been changed on " + new Date(nModif).toLocaleString() + "!", ); }); ``` 如果想要知道**目前頁面是否已變更**,請參考 `document.lastModified` (en-US) 一文。 跨網域 XMLHttpRequest ------------------ 現代瀏覽器支援跨網域(cross-site)請求並實作了網路應用程式工作小組(Web Applications (WebApps) Working Group)提出的跨網域請求存取控制標準。只要伺服器被設定為允許來自你的網路應用程式來源(origin)網域之請求,`XMLHttpRequest` 便能正常運作。否則,將會拋出一個 `INVALID_ACCESS_ERR` 例外。 避開快取 ---- 有一個跨瀏覽器相容的避開快取方法,便是將時間戳記(timestamp)附加於 URL 後方,請確保加上了適當的「?」或「&」。例如: ``` http://foo.com/bar.html -> http://foo.com/bar.html?12345 http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345 ``` 由於本地快取的索引是基於 URL,加入時間戳記會導致每一個請求都會是唯一的,藉此避開快取。 可以使用以下的程式碼來自動的調整 URL: ```js var oReq = new XMLHttpRequest(); oReq.open("GET", url + (/\?/.test(url) ? "&" : "?") + new Date().getTime()); oReq.send(null); ``` 安全性 --- 開啟跨網域指令碼(script)的建議方式是於 XMLHttpRequest 的回應中使用 `Access-Control-Allow-Origin` HTTP 標頭。 ### 被中止的 XMLHttpRequest 如果你發現 `XMLHttpRequest` 的 `status=0` 且 `statusText=null`,這代表請求並不被允許執行,其狀態為 `UNSENT(未送出)`。被中止的原因可能是因為 `XMLHttpRequest` 物件所關聯的 origin(來源網域)值(於 `XMLHttpRequest` 物件建立時自 `window.origin` 取得)在呼叫 `open()` 方法之前就已經被改變。這是可能發生的,例如在 `window` 的 `onunload` 事件觸發時送出 `XMLHttpRequest` 請求,預期的情況為:`XMLHttpRequest` 物件剛被建立,而目前的視窗尚未關閉,而最後發送請求(即呼叫了 `open()` 方法)的時間點是在此視窗失去了焦點並且另外的視窗取得焦點之間。要避開這個問題的最有效方法是在要被終止的(terminated)`window` 觸發 `unload` 事件時,於新的 `window` 的上註冊一個新的 `activate` 事件監聽器來發送請求。 使用 JavaScript 模組/XPCOM 元件中的 XMLHttpRequest ------------------------------------------ 自 JavaScript 模組 或 XPCOM 元件實體化一個 `XMLHttpRequest` 物件在做法上會有些許不同;我們無法用 `XMLHttpRequest()` 建構式,因為此建構式並未在元件中定義,並會導致程式產生錯誤。較佳的方式是使用 XPCOM 元件的建構式。 ```js const XMLHttpRequest = Components.Constructor( "@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest", ); ``` 在 Gecko 16 之前,存在著一個透過這種方式發送的請求會被無條件取消的臭蟲。若程式需要在 Gecko 15 或更早的版本上運作,可以從隱藏的 DOM window 中取得 `XMLHttpRequest()` 建構式。 ```js const { XMLHttpRequest } = Components.classes[ "@mozilla.org/appshell/appShellService;1" ].getService(Components.interfaces.nsIAppShellService).hiddenDOMWindow; var oReq = new XMLHttpRequest(); ``` 參見 -- * XMLHttpRequest 中的 HTML (en-US) * HTTP 存取控制 * XMLHttpRequest - REST and the Rich User Experience * "Using the XMLHttpRequest Object" (jibbering.com) * The `XMLHttpRequest` object: WHATWG specification
Window.print() - Web APIs
Window.print() ============== 摘要 -- 打開列印視窗來列印當前的文件。 語法 -- ``` window.print() ``` 注釋 -- Starting with Chrome V46.0 this method is blocked inside an `<iframe>` (en-US) unless its sandbox attribute has the value `allow-modals`. 規範 -- | Specification | | --- | | HTML Standard # printing | 參見 -- * Printing * `window.onbeforeprint` (en-US) * `window.onafterprint` (en-US)
Window.localStorage - Web APIs
Window.localStorage =================== **`localStorage`** 為一唯讀屬性, 此屬性允許你存取目前文件(`Document` (en-US))隸屬網域來源的 `Storage` 物件; 與 sessionStorage 不同的是其儲存資料的可存取範圍為跨瀏覽頁狀態(Browser Sessions). `localStorage` 的應用與 `sessionStorage` 相似, 除了 `localStorage` 的儲存資料並無到期的限制, 而 `sessionStorage` 的儲存資料於目前瀏覽頁狀態結束的同時將一併被清除 — 也就是目前瀏覽器頁面被關閉的同時. 值得注意的是不論 `localStorage` 或者 `sessionStorage` **皆為專屬於目前瀏覽器頁面的通訊協定(Protocol)**. 鍵值名稱和值皆為**字串型式**(請留意, 當其為物件, 整數等將自動轉換為字串型式). Syntax ------ ``` myStorage = window.localStorage; ``` ### Value `Storage` 物件 which can be used to access the current origin's local storage space. ### Exceptions `SecurityError` The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the `file:` or `data:` scheme, for example). 舉例來說,使用者 may have their browser configured to deny permission to persist data for the specified origin. Example ------- 下列的程式碼片段讀取了目前域名內的 local `Storage` 物件 ,並用`Storage.setItem()` (en-US),增加一個資料物件 item 到其中 ```js localStorage.setItem("myCat", "Tom"); ``` 讀取 `localStorage` 內物件的語法如下: ```js var cat = localStorage.getItem("myCat"); ``` 移除 `localStorage` 內物件的語法如下: ```js localStorage.removeItem("myCat"); ``` 刪除 `localStorage` 內所有物件的語法如下: ```js // Clear all items localStorage.clear(); ``` **備註:** Please refer to the Using the Web Storage API (en-US) article for a full example. Specifications -------------- | Specification | | --- | | HTML Standard # dom-localstorage-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * Using the Web Storage API (en-US) * Local storage with Window.localStorage (en-US) * `Window.sessionStorage`
Window: orientationchange event - Web APIs
Window: orientationchange event =============================== `orientationchange` 事件在設備方向改變時被觸發。 | 冒泡 | No | | --- | --- | | 可取消 | No | | 介面 | `Event` | | 事件處理器 | `onorientationchange` | 範例 -- 可於 `addEventListener` 方法中使用 `abort` 事件: ```js window.addEventListener("orientationchange", function () { console.log( "the orientation of the device is now " + screen.orientation.angle, ); }); ``` 或使用 `onorientationchange` 事件處理器屬性: ```js window.onorientationchange = function () { console.log( "the orientation of the device is now " + screen.orientation.angle, ); }; ``` 規範 -- | Specification | | --- | | Compatibility Standard # event-orientationchange | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Window.sessionStorage - Web APIs
Window.sessionStorage ===================== `sessionStorage` 屬性能讓開發人員訪問當前 origin 的 `Storage` 物件。`sessionStorage` 跟 `localStorage` 很相似:唯一不同的地方是存放在 `localStorage` 的資料並沒有過期的時效;而存放在 `sessionStorage` 的資料則會在頁面 session 結束時清空。只要該頁面頁面(頁籤)沒被關閉或者有還原(restore)該頁面,資料就會保存。**開啟新頁籤或視窗會產生一個新的 sessionStorage**,跟 Session 與 Cookies 的做法不大一樣。 另應該注意:不論資料放在 `sessionStorage` 還是 `localStorage`,都被**限制在該網站的規範內,其他網站無法存取**。 語法 -- ```js // 將資料存到sessionStorage sessionStorage.setItem("key", "value"); // 從sessionStorage取得之前存的資料 var data = sessionStorage.getItem("key"); // 從sessionStorage移除之前存的資料 sessionStorage.removeItem("key"); // 從sessionStorage移除之前存的所有資料 sessionStorage.clear(); ``` ### 回傳值 一個 `Storage` 物件. 範例 -- 下面簡短的程式碼,訪問了當前域名下的 session `Storage` 物件,並使用 `Storage.setItem()` (en-US) 添加了資料單元。 ```js sessionStorage.setItem("myCat", "Tom"); ``` 以下提供的範例為將文字輸入元件的內容自動保存,如果瀏覽器不小心重新整理,在頁面恢復後,會自動將內容還原,不會造成尚未送出的資料被清空。 ```js // 取得我們要保留內容的text field元件 var field = document.getElementById("field"); // 檢查是否有之前的autosave的內容 // 這段程式碼會在瀏覽器進入該頁面時被執行 if (sessionStorage.getItem("autosave")) { // 還原先前的內容到指定的text field field.value = sessionStorage.getItem("autosave"); } // 註冊事件監聽text field內容的變化 field.addEventListener("change", function () { // 並儲存變化後的內容至sessionStorage的物件裡 sessionStorage.setItem("autosave", field.value); }); ``` **備註:** 完整的範例可參考這篇文章: Using the Web Storage API (en-US)。 規格 -- | Specification | | --- | | HTML Standard # dom-sessionstorage-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關內容 ---- * Using the Web Storage API (en-US) * `Window.localStorage`
window.onpopstate - Web APIs
window.onpopstate ================= 摘要 -- 視窗上 popstate 事件的事件處理器。 在同一文件的當前歷史紀錄變動時,如果其變動介於兩個歷史紀錄間,`popstate` 就會被呼叫。如果當前的歷史紀錄是藉由呼叫 `history.pushState()`建立,或曾被 `history.replaceState()` 修改過,`popstate` 事件的 `state` 屬性,將包含一份歷史紀錄的 `state` 物件。 請注意:直接呼叫 `history.pushState()` 或 `history.replaceState()` 不會驅動 `popstate` 事件。`popstate` 事件只會被瀏覽器的行為驅動,例如點擊上一頁按鈕(或透過 JavaScript 呼叫 `history.back()`)。且此事件只會在用戶於同文件的兩個歷史紀錄間瀏覽時作動。 在頁面載入時,不同瀏覽器具有不同的 `popstate` 行為。Chrome 與 Safari 會在頁面載入時觸發 `popstate` 事件,但 Firefox 則不會。 語法 -- ``` window.onpopstate = funcRef; ``` * *funcRef* 是一個事件處理函數 popstate 事件 ----------- 以下範例,位於 `http://example.com/example.html` 並執行下列程式的頁面,將會產生如標示的對話框: ```js window.onpopstate = function (event) { alert( "location: " + document.location + ", state: " + JSON.stringify(event.state), ); }; history.pushState({ page: 1 }, "title 1", "?page=1"); history.pushState({ page: 2 }, "title 2", "?page=2"); history.replaceState({ page: 3 }, "title 3", "?page=3"); history.back(); // 跳出 "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // 跳出 "location: http://example.com/example.html, state: null history.go(2); // 跳出 "location: http://example.com/example.html?page=3, state: {"page":3} ``` 請注意,雖然原始的歷史紀錄(`http://example.com/example.html`)沒有關聯的 `state` 物件,在我們第二次呼叫 `history.back()` 時仍然會觸發 `popstate` 事件。 標準 -- * HTML5 popstate event 請參照 --- * `window.history` (en-US) * Manipulating the browser history * Ajax navigation example (en-US)
Window.opener - Web APIs
Window.opener ============= 概要 -- 回傳一個開啟目前視窗(window)之視窗的參考(reference)。 語法 -- ``` objRef = window.opener; ``` 範例 -- ```js if (window.opener != indexWin) { referToTop(window.opener); } ``` 備註 -- 當一個視窗是由另一個視窗所開啟(使用 `Window.open` (en-US) 或一個帶有 `target` (en-US) 屬性設定的連結),被開啟的這個視窗會於 **window.opener** 保留開啟它的第一個視窗之參考。假如目前的視窗沒有開啟它的視窗,則會回傳 NULL。 Windows Phone 瀏覽器不支援 `window.opener`(測試版本為 Microsoft Edge 25.10586.36.0)。若 `window.opener` 為不同的安全區域(security zone),則 IE 也不支援此屬性。 在 某些瀏覽器中,在發起連結的標籤中加入 `rel="noopener"` 屬性,可以阻止設定 `window.opener` 視窗參考。
HTMLElement.click() - Web APIs
HTMLElement.click() =================== **`HTMLElement.click()`** 方法可以模擬滑鼠點擊一個元素。 當 `click()` 被使用在支援的元素(例如任一 `<input>` (en-US) 元素),便會觸發該元素的點擊事件。事件會冒泡至 document tree(或 event chain)的上層元素,並觸發它們的點擊事件。其中的例外是:`click()` 方法不會讓 `<a>` (en-US) 元素和接收到真實滑鼠點擊一樣進行頁面跳轉。 語法 -- ``` elt.click() ``` 規範 -- | Specification | | --- | | HTML Standard # dom-click-dev | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
HTMLElement.lang - Web APIs
HTMLElement.lang ================ **`HTMLElement.lang`** 屬性(property)可以讀取或設定一個表示元素之語系的標籤屬性(attribute)值。 `HTMLElement.lang` 屬性所回傳的語系代碼定義於網際網路工程任務小組(IETF)的 *Tags for Identifying Languages (BCP47)* 文件中。常見的例子如 "en" 代表英語、"ja" 代表日語、"es" 代表西班牙語等等。此標籤屬性的預設值為 `unknown`。請留意,雖然此標籤屬性於個別層級的元素上是有效的,但大部分都設定於文件的根元素。 `HTMLElement.lang` 屬性只對 `lang` 標籤屬性有作用,而不是 `xml:lang`。 語法 -- ``` var languageUsed = elementNodeReference.lang; // Get the value of lang elementNodeReference.lang = NewLanguage; // Set new value for lang ``` *languageUsed* is a string variable that gets the language in which the text of the current element is written. *NewLanguage* is a string variable with its value setting the language in which the text of the current element is written. 範例 -- ```js // this snippet compares the base language and // redirects to another url based on language if (document.documentElement.lang === "en") { window.location.href = "Some\_document.html.en"; } else if (document.documentElement.lang === "ru") { window.location.href = "Some\_document.html.ru"; } ``` 規範 -- | Specification | | --- | | HTML Standard # dom-lang |
Node.innerText - Web APIs
Node.innerText ============== 概述 -- **`Node.innerText`** 是一個代表節點及其後代之「已渲染」(rendered)文字內容的屬性。如同一個存取器,`Node.innerText` 近似於使用者利用游標選取成高亮後複製至剪貼簿之元素的內容。此功能最初由 Internet Explorer 提供,並在被所有主要瀏覽器採納之後,於 2016 年正式成為 HTML 標準。 `Node.textContent` (en-US) 屬性是一個相似的選擇,但兩者之間仍有非常不同的差異。 規範 -- | Specification | | --- | | HTML Standard # the-innertext-idl-attribute | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `HTMLElement.outerText` (en-US) * `Element.innerHTML` (en-US)
製作 WebSocket 客戶端應用程式 - Web APIs
製作 WebSocket 客戶端應用程式 ==================== WebSocket 是一種讓瀏覽器與伺服器進行一段互動通訊的技術。使用這項技術的 Webapp 可以直接進行即時通訊而不需要不斷對資料更改進行輪詢(polling)。 **備註:** 當我們的系統架構可以寄存 WebSocket 範例之後,我們會提供聊天/伺服器系統實例的幾個範例。 哪裡有 WebSocket ------------- 若 JavaScript 代碼的範疇是 `Window` (en-US) 物件或是實作 `WorkerUtils` 的物件,則可使用 WebSocket API。也就是可以從 Web Workers 使用 WebSocket。 **備註:** WebSockets API(與底層協定)的開發還在進展中,且目前不同瀏覽器(甚至瀏覽器的不同版本)有很多兼容問題。 建立一個 WebSocket 物件 ----------------- 你必須建立一個 `WebSocket` 物件才能讓瀏覽器/伺服器得以以 WebSocket 協定進行通訊,此物件在被建立之後會自動與伺服器連線。 **備註:** 別忘記在 Firefox 6.0 中 `WebSocket` 物件仍有前輟,所以在這裡須改成 `MozWebSocket`。 WebSocket 的建構方法有一個必要參數與一個選擇參數: ``` WebSocket WebSocket( in DOMString url, in optional DOMString protocols ); WebSocket WebSocket( in DOMString url, in optional DOMString[] protocols ); ``` `url` 連線用的 URL,WebSocket 伺服器會回應這個 URL。 根據網際網路工程任務小組(Internet Engineering Task Force,IETF)定義之規範, URL 的協議類型必須是 `ws://` (非加密連線)或是 `wss://` (加密連線) `protocols` 選擇性 一個表示協定的字串或者是一個表示協定的字串構成的陣列。這些字串可以用來指定子協定,因此一個伺服器可以實作多個 WebSocket 子協定(舉例來說,你可以讓一個伺服器處理不同種類的互動情形,各情形以 `protocol` 分別)。若不指定協定字串則預設值為空字串。 此建構方法可能拋出以下例外: `SECURITY_ERR` 連線使用的埠被阻擋。 ### 範例 此簡單範例建立了一個新的 WebSocket,連到位於 `http://www.example.com/socketserver` 的伺服器。指定的子協定是 "my-custom-protocol"。 ``` var mySocket = new WebSocket("ws://www.example.com/socketserver", "my-custom-protocol"); ``` 回傳之後,`mySocket` 的 `readyState` 會變成 `CONNECTING`。當連線已可以傳輸資料時 `readyState` 會變成 `OPEN`。 要建立一個連線但不指定單一個特定協定,可以指定一個協定構成的陣列: ``` var mySocket = new WebSocket("ws://www.example.com/socketserver", ["protocol1", "protocol2"]); ``` 當連線建立的時候(也就是 `readyState` 變成而 `OPEN` 的時候),`protocol` 屬性會回傳伺服器選擇的協定。 傳資料給伺服器 ------- 連線開啟之後即可開始傳資料給伺服器。呼叫 `WebSocket` 的 `send()` 來發送訊息: ``` mySocket.send("這是伺服器正迫切需要的文字!"); ``` 可以被傳送的內容包括字串、`Blob` 或是 `ArrayBuffer`。 **備註:** Firefox 目前只支援字串傳送。 ### 用 JSON 傳輸物件 有一個很方便的方法是用 JSON 傳送複雜的資料給伺服器,舉例來說,聊天程式可以設計一種協定,這個協定傳送以 JSON 封裝的資料封包: ```js // 透過伺服器傳送文字給所有使用者 function sendText() { var msg = { type: "message", text: document.getElementById("text").value, id: clientID, date: Date.now(), }; mySocket.send(JSON.stringify(msg)); document.getElementById("text").value = ""; } ``` 這份代碼先建立一個物件:`msg`,它包含伺服器處理訊息所需的種種資訊,然後呼叫 `JSON.stringify()` 使該物件轉換成 JSON 格式並呼叫 WebSocket 的 `send()` 方法來傳輸資料至伺服器。 從伺服器接收訊息 -------- WebSockets 是一個事件驅動 API,當瀏覽器收到訊息時,一個「message」事件被傳入 `onmessage` 函數。使用以下方法開始傾聽傳入資料: ```js mySocket.onmessage = function (e) { console.log(e.data); }; ``` ### 接收並解讀 JSON 物件 考慮先前在「用 JSON 傳輸物件」談起的聊天應用程式。客戶端可能收到的資料封包有幾種: * 登入握手 * 訊息文字 * 更新使用者清單 用來解讀傳入訊息的代碼可能像是: ```js connection.onmessage = function (evt) { var f = document.getElementById("chatbox").contentDocument; var text = ""; var msg = JSON.parse(evt.data); var time = new Date(msg.date); var timeStr = time.toLocaleTimeString(); switch (msg.type) { case "id": clientID = msg.id; setUsername(); break; case "username": text = "<b>使用者 <em>" + msg.name + "</em> 登入於 " + timeStr + "</b><br>"; break; case "message": text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>"; break; case "rejectusername": text = "<b>由於你選取的名字已被人使用,你的使用者名稱已被設置為 <em>" + msg.name + "</em>。"; break; case "userlist": var ul = ""; for (i = 0; i < msg.users.length; i++) { ul += msg.users[i] + "<br>"; } document.getElementById("userlistbox").innerHTML = ul; break; } if (text.length) { f.write(text); document.getElementById("chatbox").contentWindow.scrollByPages(1); } }; ``` 這裡我們使用 `JSON.parse()` 使 JSON 物件轉換成原來的物件,檢驗並根據內容採取行動。 關閉連線 ---- 當你想結束 WebSocket 連線的時候,呼叫 WebSocket 的 `close()` 方法: ``` mySocket.close(); ``` 參考資料 ---- IETF: The WebSocket protocol draft-abarth-thewebsocketprotocol-01
Event.defaultPrevented - Web APIs
Event.defaultPrevented ====================== 概述 -- 回傳一個布林值,表示事件的預設行為是否被取消,也就是事件物件是否曾執行 `preventDefault()` 方法。 **備註:** You should use this instead of the non-standard, deprecated `getPreventDefault()` method (see Firefox bug 691151). 語法 -- ```js bool = event.defaultPrevented; ``` 範例 -- ```js if (e.defaultPrevented) { /\* the default was prevented \*/ } ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-defaultprevented① | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Event.bubbles - Web APIs
Event.bubbles ============= ### 概述 表示事件是否會向上冒泡傳遞。 ### 語法 ``` var bool = event.bubbles; ``` 回傳一個布林值,若事件會向上冒泡傳遞則回傳 `true`。 ### 備註 Only certain events can bubble. Events that do bubble have this property set to `true`. You can use this property to check if an event is allowed to bubble or not. ### 範例 ```js function goInput(e) { // checks bubbles and if (!e.bubbles) { // passes event along if it's not passItOn(e); } // already bubbling doOutput(e); } ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-bubbles③ |
Event.currentTarget - Web APIs
Event.currentTarget =================== `Event` 介面的唯讀屬性 **`currentTarget`** 會標明事件指向(current target)、還有該事件所遍歷的 DOM。屬性總會指向當時處理該事件的事件監聽器所註冊的 DOM 物件,而 `event.target` 屬性則是永遠指向觸發事件的 DOM 物件。 範例 -- `event.currentTarget` 在把相同的事件監聽器,附加到多個元素時,會出現很有趣的事情: ```js function hide(e) { e.currentTarget.style.visibility = "hidden"; // 在這個函式用於事件監聽器時: this === e.currentTarget } var ps = document.getElementsByTagName("p"); for (var i = 0; i < ps.length; i++) { ps[i].addEventListener("click", hide, false); } // 單擊四周的話 p 元素就會消失 ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-currenttarget② | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 事件指向的比較 (en-US)
Event.preventDefault() - Web APIs
Event.preventDefault() ====================== 概要 -- 如果事件可以被取消,就取消事件(即取消事件的預設行為)。但不會影響事件的傳遞,事件仍會繼續傳遞。 語法 -- ```js event.preventDefault(); ``` 範例 -- Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening: ```html <!doctype html> <html> <head> <title>preventDefault example</title> </head> <body> <p>Please click on the checkbox control.</p> <form> <label for="id-checkbox">Checkbox</label> <input type="checkbox" id="id-checkbox" /> </form> <script> document.querySelector("#id-checkbox").addEventListener( "click", function (event) { alert("preventDefault will stop you from checking this checkbox!"); event.preventDefault(); }, false, ); </script> </body> </html> ``` You can see `preventDefault` in action here. The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault(). ``` <!DOCTYPE html> <html> <head> <title>preventDefault example</title> <script> ``` ``` function Init() { var myTextbox = document.getElementById("my-textbox"); myTextbox.addEventListener("keypress", checkName, false); } function checkName(evt) { var charCode = evt.charCode; if (charCode != 0) { if (charCode < 97 || charCode > 122) { evt.preventDefault(); alert( "Please use lowercase letters only." + "\n" + "charCode: " + charCode + "\n", ); } } } ``` ``` </script> </head> <body onload="Init ()"> <p>Please enter your name using lowercase letters only.</p> <form> <input type="text" id="my-textbox" /> </form> </body> </html> ``` Here is the result of the preceding code: 備註 -- Calling `preventDefault` during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur. **備註:** As of Gecko 6.0, calling `preventDefault()` causes the `event.defaultPrevented` property's value to become `true`. 你可以查看 `Event.cancelable` (en-US) 屬性來檢查事件是否能夠被取消。對一個不能被取消的事件呼叫 `preventDefault()` 方法是沒有任何效果的。 `preventDefault()` 方法不會停止事件傳遞。若要停止事件繼續傳遞,可以使用 `Event.stopPropagation()` 方法。 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-preventdefault③ |
Event.target - Web APIs
Event.target ============ 指向最初觸發事件的 DOM 物件。與 `event.currentTarget` 屬性不同的是,`event.currentTarget` 屬性總會指向目前於冒泡或捕捉階段正在處理該事件之事件處理器所註冊的 DOM 物件,而 `event.target` 屬性則是永遠指向觸發事件的 DOM 物件。 語法 -- ``` theTarget = event.target ``` 範例 -- The `event.target` property can be used in order to implement **event delegation**. ```js // Make a list var ul = document.createElement("ul"); document.body.appendChild(ul); var li1 = document.createElement("li"); var li2 = document.createElement("li"); ul.appendChild(li1); ul.appendChild(li2); function hide(e) { // e.target refers to the clicked <li> element // This is different than e.currentTarget which would refer to the parent <ul> in this context e.target.style.visibility = "hidden"; } // Attach the listener to the list // It will fire when each <li> is clicked ul.addEventListener("click", hide, false); ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-target③ | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Compatibility notes ------------------- On IE 6-8 the event model is different. Event listeners are attached with the non-standard `EventTarget.attachEvent` (en-US) method. In this model, the event object has a `Event.srcElement` (en-US) property, instead of the `target` property, and it has the same semantics as `event.target`. ```js function hide(e) { // Support IE6-8 var target = e.target || e.srcElement; target.style.visibility = "hidden"; } ``` 參見 -- * Comparison of Event Targets (en-US)
Event.eventPhase - Web APIs
Event.eventPhase ================ 表示事件物件目前於事件流(Event Flow)中傳遞的進度為哪一個階段。 語法 -- ```js var phase = event.eventPhase; ``` 回傳一個整數值以代表目前事件於事件流中的傳遞階段,可能的值將於事件傳遞階段常數說明。 常數 -- ### 事件傳遞階段常數 These values describe which phase the event flow is currently being evaluated. | 常數 | 值 | 說明 | | --- | --- | --- | | `Event.NONE` Read only | 0 | No event is being processed at this time. | | `Event.CAPTURING_PHASE` Read only | 1 | The event is being propagated through the target's ancestor objects. This process starts with the `Window` (en-US), then `Document` (en-US), then the `HTMLHtmlElement` (en-US), and so on through the elements until the target's parent is reached. Event listeners registered for capture mode when `EventTarget.addEventListener()` was called are triggered during this phase. | | `Event.AT_TARGET` Read only | 2 | The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If `Event.bubbles` is false, processing the event is finished after this phase is complete. | | `Event.BUBBLING_PHASE` Read only | 3 | The event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing `Window` (en-US). This is known as bubbling, and occurs only if `Event.bubbles` is `true`. Event listeners registered for this phase are triggered during this process. | For more details, see section 3.1, Event dispatch and DOM event flow, of the DOM Level 3 Events specification. 範例 -- ### HTML ```html <h4>Event Propagation Chain</h4> <ul> <li>Click 'd1'</li> <li>Analyse event propagation chain</li> <li>Click next div and repeat the experience</li> <li>Change Capturing mode</li> <li>Repeat the experience</li> </ul> <input type="checkbox" id="chCapture" /> <label for="chCapture">Use Capturing</label> <div id="d1"> d1 <div id="d2"> d2 <div id="d3"> d3 <div id="d4">d4</div> </div> </div> </div> <div id="divInfo"></div> ``` ### CSS ```css div { margin: 20px; padding: 4px; border: thin black solid; } #divInfo { margin: 18px; padding: 8px; background-color: white; font-size: 80%; } ``` ### JavaScript ```js var clear = false, divInfo = null, divs = null, useCapture = false; window.onload = function () { divInfo = document.getElementById("divInfo"); divs = document.getElementsByTagName("div"); chCapture = document.getElementById("chCapture"); chCapture.onclick = function () { RemoveListeners(); AddListeners(); }; Clear(); AddListeners(); }; function RemoveListeners() { for (var i = 0; i < divs.length; i++) { var d = divs[i]; if (d.id != "divInfo") { d.removeEventListener("click", OnDivClick, true); d.removeEventListener("click", OnDivClick, false); } } } function AddListeners() { for (var i = 0; i < divs.length; i++) { var d = divs[i]; if (d.id != "divInfo") { d.addEventListener("click", OnDivClick, false); if (chCapture.checked) d.addEventListener("click", OnDivClick, true); d.onmousemove = function () { clear = true; }; } } } function OnDivClick(e) { if (clear) { Clear(); clear = false; } if (e.eventPhase == 2) e.currentTarget.style.backgroundColor = "red"; var level = e.eventPhase == 0 ? "none" : e.eventPhase == 1 ? "capturing" : e.eventPhase == 2 ? "target" : e.eventPhase == 3 ? "bubbling" : "error"; divInfo.innerHTML += e.currentTarget.id + "; eventPhase: " + level + "<br/>"; } function Clear() { for (var i = 0; i < divs.length; i++) { if (divs[i].id != "divInfo") divs[i].style.backgroundColor = i & 1 ? "#f6eedb" : "#cceeff"; } divInfo.innerHTML = ""; } ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-eventphase③ |
Event.isTrusted - Web APIs
Event.isTrusted =============== `Event` 介面的 `isTrusted` 唯讀屬性為一個布林值,若事件物件是由使用者操作而產生,則 `isTrusted` 值為 `true`。若事件物件是由程式碼所建立、修改,或是透過 `EventTarget.dispatchEvent()` 來觸發,則 `isTrusted` 值為 `false`。 語法 -- ``` var bool = event.isTrusted; ``` 範例 -- ``` if (e.isTrusted) { /* The event is trusted. */ } else { /* The event is not trusted. */ } ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-istrusted① | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Event() - Web APIs
Event() ======= **`Event()`** constructor 能用來建立一個 `事件` 。 語法 -- ``` event = new Event(typeArg, eventInit); ``` ### 參數 *typeArg* 為一 `DOMString` ,用來表示事件名稱。 *eventInit*選擇性 一個 `EventInit` object,包含以下欄位 | 參數 | 可選 | 默認值 | 類型 | 說明 | | --- | --- | --- | --- | --- | | `"bubbles"` | ● | `false` | `Boolean` | 表示該事件是否懸浮(bubble up)。 | | `"cancelable"` | ● | `false` | `Boolean` | 表示該事件是否已取消(canale)。 | 範例 -- ```js // 建立一個 bubbles up 、並未被取消的事件 「look」 。 var ev = new Event("look", { bubbles: true, cancelable: false }); document.dispatchEvent(ev); ``` 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-event | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Event`
Event.type - Web APIs
Event.type ========== **`Event.type`** 唯讀屬性會回傳一個代表此事件物件類型的字串。`Event.type` 屬性是於事件物件建立時被設定,而其屬性值-事件類型名稱也常被當作是特定的事件。 傳至 `EventTarget.addEventListener()` 和 `EventTarget.removeEventListener()` (en-US) 方法中,代表事件類型的參數 *`event`* 是不區分大小寫的。 可用的事件類型,可參考 event reference。 語法 -- ``` event.type ``` 範例 -- ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Event.type Example</title> <script> var currEvent = null; function getEvtType(evt) { console.log("//Start------------getEvtType(evt)------------ "); currEvent = evt.type; console.log(currEvent); //document.getElementById("Etype").firstChild.nodeValue = currEvent; document.getElementById("Etype").innerHTML = currEvent; console.log("//End--------------getEvtType(evt)------------ "); } //Keyboard events document.addEventListener("keypress", getEvtType, false); //[second] document.addEventListener("keydown", getEvtType, false); //first document.addEventListener("keyup", getEvtType, false); //third //Mouse events document.addEventListener("click", getEvtType, false); // third document.addEventListener("mousedown", getEvtType, false); //first document.addEventListener("mouseup", getEvtType, false); //second </script> </head> <body> <p>Press any key or click the mouse to get the event type.</p> <p>Event type: <span id="Etype" style="color:red">-</span></p> </body> </html> ``` ### Result 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-type④ |
Event.timeStamp - Web APIs
Event.timeStamp =============== 說明 -- 回傳事件建立的時間(單位是毫秒;從 epoch 開始計算)。 Syntax ------ ``` event.timeStamp ``` 範例 -- ``` var number = event.timeStamp; ``` 下面是一個較為完整的範例: ```html <html> <head> <title>timeStamp example</title> <script type="text/javascript"> function getTime(event) { document.getElementById("time").firstChild.nodeValue = event.timeStamp; } </script> </head> <body onkeypress="getTime(event)"> <p>Press any key to get the current timestamp for the onkeypress event.</p> <p>timeStamp: <span id="time">-</span></p> </body> </html> ``` 注意 -- 這個 property 僅在瀏覽器支持該事件才會有用。 詳細資料 ---- * timestamp
Event.stopImmediatePropagation() - Web APIs
Event.stopImmediatePropagation() ================================ 除了停止事件繼續捕捉或冒泡傳遞外,也阻止事件被傳入同元素中註冊的其它相同事件類型之監聽器。 語法 -- ``` event.stopImmediatePropagation(); ``` 備註 -- 如果一個元素中註冊了多個相同事件類型的監聽器,監聽器將會按照註冊的先後順序被呼叫。在其中任何一個監聽器執行的期間,若是呼叫了事件物件的 `stopImmediatePropagation()` 方法,則接下來尚未執行的監聽器皆不會被呼叫。 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-stopimmediatepropagation① | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Event.stopPropagation() - Web APIs
Event.stopPropagation() ======================= `Event` 介面的 **`stopPropagation()`** 方法可阻止當前事件繼續進行捕捉(capturing)及冒泡(bubbling)階段的傳遞。 語法 -- ``` event.stopPropagation(); ``` 範例 -- 請參考範例五:事件傳遞 (en-US)章節中關於此方法與 DOM 事件傳遞的更詳細範例。 規範 -- | Specification | | --- | | DOM Standard # ref-for-dom-event-stoppropagation① | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * See the DOM specification for the explanation of event flow. (The DOM Level 3 Events draft has an illustration.) * `Event.preventDefault()` is a related method that prevents the default action of the event from happening.
WebGL tutorial - Web APIs
WebGL tutorial ============== WebGL 讓網頁內容可以使用一個基於 OpenGL ES 2.0 的 API 以在 HTML `<canvas>`中執行 3D 渲染,且瀏覽器無需使用任何 plug-in。WebGL programs 由 JavaScript 撰寫的指令碼以及透過電腦的 Graphics Processing Unit (GPU)上運行的特殊效果程式碼(shader code)組成。WebGL 元件可與其他 HTML 元件混合,並與該頁的其他部分或該頁背景組合使用。 本教學描述如何使用 `<canvas>` 元件描繪 WebGL 圖像/圖形, 從基礎開始。提供的範例將讓你對於可以用 WebGL 做到什麼有清楚的概念,並提供程式碼片段讓你可以著手建立自己的內容。 開始之前 ---- 使用`<canvas>` 元件不會非常困難,但你需要有對HTML 與 JavaScript 的基礎認識。`<canvas>` 元件跟 WebGL 在某些舊瀏覽器中不支援,但近來的每個主流瀏覽器都有支援。我們用 JavaScript context object 在 canvas 繪製圖形,這樣圖形就能動態(on the fly)產生。 教學文件 ---- WebGL 新手上路 如何建置 WebGL 環境 加入 2D 內容至 WebGL 環境 如何用 WebGL 渲染簡單平面的形狀 使用 shaders 在 WebGL 上色 (en-US) 示範如何使用 shaders 在圖形上上色 WebGL 產生動畫 (en-US) 示範如何旋轉與移動物件以製作簡單的動畫 建立三維物件 (en-US) 示範如何創造並讓 3D 物件(立方體)有動畫 在物件表面貼上材質 (en-US) 示範如何在物件的表面上貼上材質圖 模擬打光 (en-US) 如何在 WebGL 環境模擬打光效果 讓材質產生動畫 (en-US) 如何移動材質圖,在範例中是將 Ogg 影片 貼到一個旋轉中的立方體
WebGL 入門 - Web APIs
WebGL 入門 ======== * 次頁 » WebGL 讓網頁內容能藉由一種基於 OpenGL ES 2.0 的 API 的幫助,於支援此 API 的瀏覽器環境中,不需使用外掛程式就能在 HTML 的 `canvas` 元素中實現二維及三維渲染。 WebGL 程式包含了由 JavaSrcipt 及著色器(GLSL)撰寫的控制碼以及在電腦的圖形處理器( GPU )上執行的特效程式碼(著色器程式碼)。WebGL 元素可以加入其他 HTML 元素之中並與網頁或網頁背景的其他部分混合。 這篇文章將會向你介紹 WebGL 的基礎。這篇文章假設你已經對於三維圖學涉及的數學有所了解,並且它將不會被佯裝為三維圖學的教材。在我們的學習區域內有初學者指南讓你完成編程任務:Learn WebGL for 2D and 3D graphics. 在此教學文件中的程式碼範例都能在 webgl-examples GitHub repository 之中找到。 準備三維渲染 ------ 首先你需要一個 canvas 元素讓 WebGL 進行渲染。下面的 HTML 定義的 canvas 元素供後續的範例繪製。 ```html <body> <canvas id="glCanvas" width="640" height="480"></canvas> </body> ``` ### 準備 WebGL 背景資料 **備註:** 背景資料為 Context 翻譯而來 在下面的 JavaScript 程式碼,當指令完成讀取後會執行 `main()` 函式。目的是為了設定 WebGL 背景資料並且開始渲染內容。 ```js main(); // 從這開始 function main() { const canvas = document.querySelector("#glCanvas"); // 初始化 GL context const gl = canvas.getContext("webgl"); // 當 WebGL 有效才繼續執行 if (gl === null) { alert("無法初始化 WebGL,你的瀏覽器不支援。"); return; } // 設定清除色彩為黑色,完全不透明 gl.clearColor(0.0, 0.0, 0.0, 1.0); // 透過清除色來清除色彩緩衝區 gl.clear(gl.COLOR\_BUFFER\_BIT); } ``` 在此我們做的第一件事是取得 canvas 元素的參考,並存入 canvas 變數中。 一旦我們取得了 canvas ,我們透過呼叫 getContext (en-US) 並傳入 `"webgl"` 字串來取得 WebGLRenderingContext (en-US)。若瀏覽器不支援 webgl `getContext` 會回傳 `null` 同時會顯示訊息給使用者並且離開。 如果成功初始化, `gl` 就會成為一個 WebGL 背景資料的參考。在這裡我們設置清除色為黑色,並透過該色清除 context (用背景色重新繪製 canvas )。 至此,你已經有足夠初始化 WebGL 背景資料的程式碼,並且準備好了等待接收內容的容器。 檢視完整程式碼 | 開啟新頁面來檢視結果 亦可參考 ---- * An introduction to WebGL: 由 Luz Caballero 撰寫,並出版在 dev.opera.com。 這篇文章點出了 WebGL 的意義,解釋了其運作(包含渲染管路的觀念),並介紹了一些 WebGL libraries。 * WebGL Fundamentals * An intro to modern OpenGL: 由 Joe Groff 撰寫的一系列關於 OpenGL 的好文章,提供了 OpenGL 清楚的簡介,從其歷史到重要的圖像管路概念,以及一些展示其原理的範例。如果你完全不懂 OpenGL,這將是一個好的入門介紹。 * 次頁 »
增加一個 2D 物件到 WebGL 環境 - Web APIs
增加一個 2D 物件到 WebGL 環境 ==================== * « 前頁 * 次頁 » (en-US) 當你建立了 WebGL 的 context後,便可開始渲染。最簡單的例子就是加入一個普通的正方形。接下來,我們會介紹如何畫一個正方形。 畫場景 --- 首先我們需要知道雖然這個範例只是要畫一個正方形,但我們還是在 3D 的空間裡作圖。基本上,我們就是畫一個正方形並把它放在相機前面,使正方形與使用者的視角垂直。我們要定義一個 shader,透過它來渲染我們的物件。接下來,我們會展示如何在螢幕前顯示一個正方形。 ### Shader WebGL Shader 使用 OpenGL ES Shading Language。 這邊不討論 shader 的細節的,但簡而言之,我們需要定義兩個 shader (GPU 上可執行的函數): vertex shader 和 fragment shader。這兩個 shader 會以字串的形式傳入 WebGL,編譯後在 GPU 上執行。 #### Vertex shader Vertex shader 是用來定義一個變數 gl\_Position 的值來控制畫布空間的值(-1 到+1),下面的範例,我們設了一個變數`aVertexPosition`用來記錄 vertex 的位置。接下來我們將該位置乘上兩個 4x4 的矩陣(`uProjectionMatrix`和`uModelMatrix`),並將結果設定為 gl\_Position 的值。如果想要了解更多關於 Projection 和其他矩陣可以參閱這篇文件。 ```js // Vertex shader program const vsSource = ` attribute vec4 aVertexPosition; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; void main() { gl\_Position = uProjectionMatrix \* uModelViewMatrix \* aVertexPosition; } `; ``` #### Fragment shader 每次 vertex shader 給 gl\_Position 1 到 3 個值的時候,它會分別畫出點、線、三角形。畫圖的時候,會呼叫 fragment shader 來詢問每個 pixel 的顏色。在這個範例中,我們對於每次詢問都回傳白色。 `gl_FragColor` 是 GL 預設的變數用來定義每個 fragment 的顏色,透過設定該變數的值來定義每個 pixel 的顏色,如下: ```js const fsSource = ` void main() { gl\_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } `; ``` ### 初始化 shader 現在我們已經定義了兩個 shader ,我們接下來要將它們傳入 WebGL,編譯並連結。下面的程式碼呼叫了 loadShader 來建立兩個 shader。接下來,我們要新增一個程式,並將 shader 加入該程式,並將程式連結起來。如果編譯或連接失敗,程式碼會顯示錯誤訊息。 ```js // // 初始化 shader 來告知WebGL怎麼畫 // function initShaderProgram(gl, vsSource, fsSource) { const vertexShader = loadShader(gl, gl.VERTEX\_SHADER, vsSource); const fragmentShader = loadShader(gl, gl.FRAGMENT\_SHADER, fsSource); // 建立 shader 程式 const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // 錯誤處理 if (!gl.getProgramParameter(shaderProgram, gl.LINK\_STATUS)) { alert( "Unable to initialize the shader program: " + gl.getProgramInfoLog(shaderProgram), ); return null; } return shaderProgram; } // // creates a shader of the given type, uploads the source and // compiles it. // function loadShader(gl, type, source) { const shader = gl.createShader(type); // Send the source to the shader object gl.shaderSource(shader, source); // Compile the shader program gl.compileShader(shader); // See if it compiled successfully if (!gl.getShaderParameter(shader, gl.COMPILE\_STATUS)) { alert( "An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader), ); gl.deleteShader(shader); return null; } return shader; } ``` 我們可以透過呼叫 initShaderProgram 來建立 shader 程式 ```js const shaderProgram = initShaderProgram(gl, vsSource, fsSource); ``` 接下來我們需要找到 WebGL 生成出的位置。這個例子中我們有一個 attribute、兩個 uniform。 Attributes 從 buffer 獲得值。每次迭代時,vertex shader 從 buffer 得到下一個值並傳入到 attribute。 Uniform 則像是 Javascript 的全域變數。每次迭代,他們的值不會改變。為了之後方便,我們將 shader 程式與 attribute 和 uniform 存放在同一個物件中。 ```js const programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"), }, uniformLocations: { projectionMatrix: gl.getUniformLocation(shaderProgram, "uProjectionMatrix"), modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"), }, }; ``` 建立正方形平面 ------- 在我們渲染前,我們要建立一個 buffer 用來儲存頂點的座標。在此我們宣告一個函數 `initBuffers()` ,隨著之後建立更多複雜的物件,這個動作會重複見到很多次。 ```js function initBuffers(gl) { // 建立一個 buffer 來儲存正方形的座標 const positionBuffer = gl.createBuffer(); // Select the positionBuffer as the one to apply buffer // operations to from here out. gl.bindBuffer(gl.ARRAY\_BUFFER, positionBuffer); // Now create an array of positions for the square. const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0]; // Now pass the list of positions into WebGL to build the // shape. We do this by creating a Float32Array from the // JavaScript array, then use it to fill the current buffer. gl.bufferData(gl.ARRAY\_BUFFER, new Float32Array(positions), gl.STATIC\_DRAW); return { position: positionBuffer, }; } ``` 這個步驟非常簡單,一開始呼叫`gl`物件的函數 `createBuffer()` (en-US) 來產生一個儲存座標的 buffer,並將將該 buffer 綁定 WebGL 的 context。 完成後,我們宣告一個陣列來儲存正方形平面各頂點的座標,並轉型為浮點數陣列並用`bufferData()` (en-US)函數傳入 `gl` 物件。 渲染場景 ---- Shader 建立好了、位置也確定好了、正方形平面頂點的位置也已經放到 buffer 後,我們就可以實際來渲染場景了。因為這個例子沒有任何的動畫,`drawScene()`函數非常單純。 ```js function drawScene(gl, programInfo, buffers) { gl.clearColor(0.0, 0.0, 0.0, 1.0); // 設定為全黑 gl.clearDepth(1.0); // 清除所有東西 gl.enable(gl.DEPTH\_TEST); // Enable 深度測試 gl.depthFunc(gl.LEQUAL); // Near things obscure far things // 開始前先初始化畫布 gl.clear(gl.COLOR\_BUFFER\_BIT | gl.DEPTH\_BUFFER\_BIT); // Create a perspective matrix, a special matrix that is // used to simulate the distortion of perspective in a camera. // Our field of view is 45 degrees, with a width/height // ratio that matches the display size of the canvas // and we only want to see objects between 0.1 units // and 100 units away from the camera. const fieldOfView = (45 \* Math.PI) / 180; // in radians const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; const zNear = 0.1; const zFar = 100.0; const projectionMatrix = mat4.create(); // note: glmatrix.js always has the first argument // as the destination to receive the result. mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar); // Set the drawing position to the "identity" point, which is // the center of the scene. const modelViewMatrix = mat4.create(); // Now move the drawing position a bit to where we want to // start drawing the square. mat4.translate( modelViewMatrix, // destination matrix modelViewMatrix, // matrix to translate [-0.0, 0.0, -6.0], ); // amount to translate // Tell WebGL how to pull out the positions from the position // buffer into the vertexPosition attribute. { const numComponents = 2; // pull out 2 values per iteration const type = gl.FLOAT; // the data in the buffer is 32bit floats const normalize = false; // don't normalize const stride = 0; // how many bytes to get from one set of values to the next // 0 = use type and numComponents above const offset = 0; // how many bytes inside the buffer to start from gl.bindBuffer(gl.ARRAY\_BUFFER, buffers.position); gl.vertexAttribPointer( programInfo.attribLocations.vertexPosition, numComponents, type, normalize, stride, offset, ); gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition); } // Tell WebGL to use our program when drawing gl.useProgram(programInfo.program); // Set the shader uniforms gl.uniformMatrix4fv( programInfo.uniformLocations.projectionMatrix, false, projectionMatrix, ); gl.uniformMatrix4fv( programInfo.uniformLocations.modelViewMatrix, false, modelViewMatrix, ); { const offset = 0; const vertexCount = 4; gl.drawArrays(gl.TRIANGLE\_STRIP, offset, vertexCount); } } ``` 第一步,我們先將畫布背景設定為黑色,並設定相機的視角。我們將角度設為 45°,並設定成與畫布的長寬比相同。另外我們指定我們只要渲染離相機 0.1 ~ 100 單位遠的物件。 接下來,我們讀入正方形的位置,並把它擺在離相機 6 單位遠的位置。然後我們將正方形頂點的 buffer 綁定到 gl 上。最後我們呼叫`drawArrays()` (en-US)函數來渲染物件。 檢視完整程式碼 | 開啟新頁面來檢視結果 矩陣運算 ---- 矩陣的運算看起來很複雜,但其實一步一步運算其實不會那麼困難。大部分使用者不會寫自己的運算函數,多半是使用現成的矩陣函數庫,這個例子中我們用的是 glMatrix library 。 可參考以下資料 * Matrices on WebGLFundamentals * Matrices on Wolfram MathWorld * Matrix on Wikipedia * « 前頁 * 次頁 » (en-US)
XMLHttpRequest.setRequestHeader() - Web APIs
XMLHttpRequest.setRequestHeader() ================================= `XMLHttpRequest` 物件中的 **`setRequestHeader()`** 方法用來設定 HTTP 的表頭請求。當使用 `setRequestHeader()` 的時候,必須在 `open()` (en-US) 之後呼叫,同時也必須在 `send()` (en-US) 之前呼叫。如果這個方法被呼叫了許多次,且設定的表頭是一樣的,那所有設定的值會被合併成一個單一的表頭請求。 在第一次呼叫 `setRequestHeader()` 之後的每一次的呼叫,都會把給定的文字附加在已存在的表頭內容之後。 If no `Accept` header has been set using this, an `Accept` header with the type `"*/*"` is sent with the request when `send()` (en-US) is called. 基於安全的理由,有些表頭只有使用者代理器可以使用。這些表頭包含了: forbidden header names (en-US) 和 forbidden response header names (en-US). **備註:** For your custom fields, you may encounter a "**not allowed by Access-Control-Allow-Headers in preflight response**" exception when you send requests across domains. In this situation, you need to set up the `Access-Control-Allow-Headers` (en-US) in your response header at server side. 語法 -- ``` XMLHttpRequest.setRequestHeader(header, value) ``` ### 參數 `header` 想要設定所屬值的表頭名稱。 `value` 用來設定表頭本身的值。 ### 回傳值 未定義。 規範 -- | Specification | | --- | | XMLHttpRequest Standard # the-setrequestheader()-method | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 使用 XMLHttpRequest * HTML in XMLHttpRequest (en-US)
XMLHttpRequest.status - Web APIs
XMLHttpRequest.status ===================== **XMLHttpRequest.status** 屬性根據 XMLHttpRequest 的回應傳回數值化的狀況編碼。狀況編碼為一正短整數(`unsigned short)。`Before the request is complete, the value of `status` will be `0`. It is worth noting that browsers report a status of 0 in case of XMLHttpRequest errors too. The status codes returned are the standard HTTP status codes. For example, `status` `200` denotes a successful request. If the server response doesn't explicitly specify a status code, `XMLHttpRequest.status` will assume the default value of `200`. Example ------- ```js var xhr = new XMLHttpRequest(); console.log("UNSENT", xhr.status); xhr.open("GET", "/server", true); console.log("OPENED", xhr.status); xhr.onprogress = function () { console.log("LOADING", xhr.status); }; xhr.onload = function () { console.log("DONE", xhr.status); }; xhr.send(null); /\*\* \* Outputs the following: \* \* UNSENT 0 \* OPENED 0 \* LOADING 200 \* DONE 200 \*/ ``` Specifications -------------- | Specification | | --- | | XMLHttpRequest Standard # the-status-attribute | Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * List of HTTP response codes
XMLHttpRequest() - Web APIs
XMLHttpRequest() ================ **`XMLHttpRequest()`** 建構式會建立一個新的 `XMLHttpRequest` 物件。 關於如何使用 `XMLHttpRequest` 物件的細節,請參照:使用 XMLHttpRequest。 語法 -- ```js const request = new XMLHttpRequest(); ``` ### 參數 無。 ### 回傳值 將回傳一個新的 `XMLHttpRequest` 物件。`XMLHttpRequest` 物件在呼叫`send()` (en-US) 送出要求到伺服器之前,至少要藉著呼叫 `open()` (en-US) 來準備好必需的設定。 非標準的 Firefox 語法 --------------- Firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see Firefox bug 692677). Setting the `mozAnon` flag to `true` effectively resembles the `AnonXMLHttpRequest()` constructor described in older versions of the XMLHttpRequest specification. ```js const request = new XMLHttpRequest(paramsDictionary); ``` ### Parameters (non-standard) `objParameters` There are two flags you can set: `mozAnon` Boolean: Setting this flag to `true` will cause the browser not to expose the origin (en-US) and user credentials when fetching resources. Most important, this means that cookies will not be sent unless explicitly added using setRequestHeader. `mozSystem` Boolean: Setting this flag to `true` allows making cross-site connections without requiring the server to opt-in using CORS. *Requires setting `mozAnon: true`, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps (Firefox bug 692677); it does not work on arbitrary webpages loaded in Firefox* 參見 -- * 使用 XMLHttpRequest * HTML in XMLHttpRequest (en-US)
XMLHttpRequest.withCredentials - Web APIs
XMLHttpRequest.withCredentials ============================== **`XMLHttpRequest.withCredentials`** 屬性是一個 `Boolean` 型別,它指出無論是否使用 `Access-Control` 標頭在跨站的要求上,都應該使用像 Cookies、Authorization 標頭或 TLS 用戶端憑證來進行驗證。在相同來源的要求設定 `withCredentials` 沒有任何效果。 In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is `false`. `XMLHttpRequest` from a different domain cannot set cookie values for their own domain unless `withCredentials` is set to `true` before making the request. The third-party cookies obtained by setting `withCredentials` to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie (en-US) or from response headers. **備註:** 永遠不會影響到同源請求。 **備註:** `XMLHttpRequest` responses from a different domain *cannot* set cookie values for their own domain unless `withCredentials` is set to `true` before making the request, regardless of `Access-Control-` header values. 範例 -- ```js var xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com/", true); xhr.withCredentials = true; xhr.send(null); ``` 規格 -- | Specification | | --- | | XMLHttpRequest Standard # the-withcredentials-attribute | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
XMLHttpRequest.readyState - Web APIs
XMLHttpRequest.readyState ========================= **XMLHttpRequest.readyState** 屬性會回傳一個 XMLHttpRequest 客戶端物件目前的狀態。一個 XHR 客戶端可以為下列其中一種狀態: | 值 | 狀態 | 說明 | | --- | --- | --- | | `0` | `UNSENT` | 客戶端已被建立,但 `open()` 方法尚未被呼叫。 | | `1` | `OPENED` | `open()` 方法已被呼叫。 | | `2` | `HEADERS_RECEIVED` | `send()` 方法已被呼叫,而且可取得 header 與狀態。 | | `3` | `LOADING` | 回應資料下載中,此時 `responseText` 會擁有部分資料。 | | `4` | `DONE` | 完成下載操作。 | UNSENT XMLHttpRequest 客戶端物件已被建立,但 open() 方法尚未被呼叫。 OPENED open() 方法已被呼叫。於此狀態時,可以使用 setRequestHeader() 方法設定請求標頭(request headers),並可呼叫 send() (en-US) 方法來發送請求。 HEADERS\_RECEIVED send() 方法已被呼叫,並且已接收到回應標頭(response header)。 LOADING 正在接收回應內容(response's body)。如 `responseType` (en-US) 屬性為 "text" 或空字串,則 `responseText` (en-US) 屬性將會在載入的過程中擁有已載入部分之回應(response)內容中的文字。 DONE 請求操作已完成。這意味著資料傳輸可能已成功完成或是已失敗。 **備註:** 這些狀態名稱在 Internet Explorer 中略有不同。其中 `UNSENT`, `OPENED`, `HEADERS_RECEIVED`, `LOADING` 和 `DONE` 變成了 `READYSTATE_UNINITIALIZED` (0), `READYSTATE_LOADING` (1), `READYSTATE_LOADED` (2), `READYSTATE_INTERACTIVE` (3) 和`READYSTATE_COMPLETE` (4)。 範例 -- ```js var xhr = new XMLHttpRequest(); console.log("UNSENT", xhr.readyState); // readyState will be 0 xhr.open("GET", "/api", true); console.log("OPENED", xhr.readyState); // readyState will be 1 xhr.onprogress = function () { console.log("LOADING", xhr.readyState); // readyState will be 3 }; xhr.onload = function () { console.log("DONE", xhr.readyState); // readyState will be 4 }; xhr.send(null); ``` 規範 -- | Specification | | --- | | XMLHttpRequest Standard # states | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
怪異模式與標準模式 - HTML:超文本標記語言
怪異模式與標準模式 ========= 很久以前,網頁通常有兩種版本:針對網景(Netscape)的 Navigator 的版本,以及針對微軟(Microsoft)的 Internet Explorer 的版本。在 W3C 創立網路標準後,為了不破壞當時既有的網站,瀏覽器不能直接起用這些標準。因此,瀏覽器導入了能分辨符合新規範、或屬於老舊網站的兩種模式。 目前瀏覽器的排版引擎有三種模式:怪異模式(Quirks mode)、接近標準模式(Almost standards mode)、以及標準模式(Standards mode)。在**怪異模式**,排版會模擬 Navigator 4 與 Internet Explorer 5 的非標準行為。為了支持在網路標準被廣泛採用前,就已經建置好的網站,這麼做是必要的。在**標準模式**,行為(期待)由 HTML 與 CSS 的規範描述起來。在**接近標準模式**,有少數的怪異行為被實行。 瀏覽器如何決定用哪個模式? ------------- 對 HTML 文件來說,瀏覽器使用文件開頭的 DOCTYPE 來決定用怪異模式處理或標準模式處理。為了確保頁面使用標準模式,請確認你的頁面,如同本範例一樣擁有 DOCTYPE: ```html <!doctype html> <html> <head> <meta charset="UTF-8" /> <title>Hello World!</title> </head> <body></body> </html> ``` 範例中的 `<!DOCTYPE html>` 是所有可用之中最簡單、並由 HTML5 推薦的。HTML 的早期變種也屬於推薦標準,不過今日的瀏覽器都會對這個 DOCTYPE 使用標準模式,就算是已過時的 Internet Explorer 6 也一樣。目前並沒有正當理由,去使用其他更複雜的 DOCTYPE。如果使用其他 DOCTYPE,可能會冒著觸發接近標準模式、或著怪異模式的風險。 請確定把 DOCTYPE 正確地放在 HTML 文件頂端。任何放在 DOCTYPE 前面的東西,如註解或 XML 聲明,會令 Internet Explorer 9 或更早期的瀏覽器觸發怪異模式。 在 HTML5,DOCTYPE 唯一的作用是啟用標準模式。更早期的 HTML 標準會附加其他意義,但沒有任何瀏覽器會用 DOCTYPE 去做模式間互換以外的用途。 另請參閱不同的瀏覽器選擇不同模式的詳細說明。 ### XHTML 如果你的網頁使用 XHTML 並在 `Content-Type` HTTP 標頭使用 `application/xhtml+xml` MIME 類型,你不需要使用 DOCTYPE 啟動標準模式,因為這種文件會永遠使用標準模式。不過請注意服務頁面使用 `application/xhtml+xml` 會令 Internet Explorer 8 出於未知格式之故出現下載對話框,支持 XHTML 的第一個 Internet Explorer 版本是 Internet Explorer 9。 如果你的類 XHTML 網頁使用 `text/html` MIME 類型,瀏覽器會視為 HTML,你就需要 DOCTYPE 啟用標準模式。 我要如何知道目前是哪個模式? -------------- 在 Firefox,請從右鍵選單選擇*觀看頁面資訊*,然後查看*繪製模式*。 在 Internet Explorer,請按下 *F12*,然後查看*文件模式*. 這些模式有何不同? --------- 請參閱怪異模式的清單還有接近標準模式的清單之間的差別。
HTML 參考 - HTML:超文本標記語言
HTML 參考 ======= 這裡的 HTML 參考描述了所有 HTML 的**元素**(elements)與**屬性**(attributes),包括為所有元素接受的**全域屬性**(global attributes)。 HTML 元素指引 (en-US) 本頁列出了所有 HTML elements HTML 屬性指引 HTML 中的元素具有屬性 ; 而這些屬性可以藉由各種方式去設定元素或調整它們的行為,以符合使用者的期待。 全域屬性 (en-US) Global attributes may be specified on all HTML elements, even those not specified in the standard. That means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer HTML5-compliant. For example, HTML5-compliant browsers hide content marked as <foo hidden>...<foo>, even though <foo> is not a valid HTML element. 連結類型 In HTML, the following link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, or <link> element.
HTML attribute reference - HTML:超文本標記語言
HTML attribute reference ======================== HTML 中的元素具有**屬性**;而這些屬性可以藉由各種方式去設定元素或調整它們的行為,以符合使用者的期待。 屬性列表 ---- | 屬性名稱 | 元素 | 描述 | | --- | --- | --- | | `hidden` | Global attribute | 避免呈現給定的元素,並且保持子元素,例如 script elements、active。 | | `high` | `<meter>` (en-US) | 指示下界的上限範圍。 | | `href` | `<a>` (en-US)、`<area>` (en-US)、`<base>` (en-US)、`<link>` (en-US) | 連結資源的 URL。 | | `hreflang` | `<a>` (en-US)、`<area>` (en-US)、`<link>` (en-US) | 指定連結資源的語言。 | | `http-equiv` | `<meta>` (en-US) | | | `icon` | `<command>` | 指定呈現指令的圖片。 | | `id` | Global attribute | 經常和 CSS 一起被用來設計特定元素。這個屬性的值必須是唯一的。 | | `ismap` | `<img>` (en-US) | 指示該圖像是伺服器端之影像地圖的一部分。 | | `itemprop` | Global attribute | | | `kind` | `<track>` (en-US) | 指明文章 track 的類型。 | | `label` | `<track>` (en-US) | 指明文章 track 的使用者可讀之標題。 | | `lang` | Global attribute | 定義該元素中所使用的語言。 | | `language` | `<script>` | 定義該元素中所使用的腳本語言。 | | `list` | `<input>` (en-US) | 指示一串預先定義的選項供使用者參考。 | | `loop` | `<audio>` (en-US)、`<marquee>`、`<video>` (en-US) | 指示當媒體完成時,是否應該從一開始的時候播放。 | | `low` | `<meter>` (en-US) | 指示上界的下限範圍。 | | `manifest` | `<html>` (en-US) | 指定文件中緩存清單的 URL。 | | `max` | `<input>` (en-US)、`<meter>` (en-US)、`<progress>` (en-US) | 指示所允許的最大值。 | | `maxlength` | `<input>` (en-US)、`<textarea>` (en-US) | 定義該元素中所允許的最大字元數目。 | | `media` | `<a>` (en-US)、`<area>` (en-US)、`<link>` (en-US)、`<source>` (en-US)、`<style>` (en-US) | 指定一些連接資源已經被設計的媒體。 | | `method` | `<form>` (en-US) | 定義當呈交該格式時,哪個 HTTP 方法要被使用。可以用 GET(預設)或是 POST。 | | `min` | `<input>` (en-US)、`<meter>` (en-US) | 指示所允許的最小值。 | | `multiple` | `<input>` (en-US)、`<select>` (en-US) | 指示多個值是否可以進入單一輸入的 `email` 或是 `file` 之類別。 | | `name` | `<button>` (en-US)、`<form>` (en-US)、`<fieldset>` (en-US)、`<iframe>` (en-US)、`<input>` (en-US)、`<object>` (en-US)、`<output>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US)、`<map>` (en-US)、`<meta>` (en-US)、`<param>` (en-US) | 元素的名字。例如被伺服器所使用時,來識別格式提交的現場。 | | `novalidate` | `<form>` (en-US) | 該屬性指示當本格式被提交時,並無法通過驗證。 | | `open` | `<details>` (en-US) | 指示是否細節顯示於加載頁面上。 | | `optimum` | `<meter>` (en-US) | 指示最佳化數值。 | | `pattern` | `<input>` (en-US) | 定義一個元素值將被驗證的正規表達式。 | | `ping` | `<a>` (en-US)、`<area>` (en-US) | | | `placeholder` | `<input>` (en-US)、`<textarea>` (en-US) | 提示使用者什麼可以被輸入進該區。 | | `poster` | `<video>` (en-US) | 顯現一個指示 poster frame 的 URL,直到使用者撥放或是搜索。 | | `preload` | `<audio>` (en-US)、`<video>` (en-US) | 指示是否整個資源、一部分的資源、或是沒有資源應該被預先裝載。 | | `pubdate` | `<time>` | 指示該日期和時間,是否和距離最近的 `<article>` (en-US) 舊元素的日期一樣。 | | `radiogroup` | `<command>` | | | `readonly` | `<input>` (en-US)、`<textarea>` (en-US) | 指示是否該元素可以被編輯。 | | `rel` | `<a>` (en-US)、`<area>` (en-US)、`<link>` (en-US) | 指定目標物件和連結物驗的關係。 | | `required` | `<input>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US) | 指示該元素是否被要求填寫。 | | `reversed` | `<ol>` (en-US) | 指示該目錄是否應以降序展出而不是升序。 | | `rows` | `<textarea>` (en-US) | 定義 textarea 的行數。 | | `rowspan` | `<td>` (en-US)、`<th>` (en-US) | 定義表格單元的行數應該被 span over。 | | `sandbox` | `<iframe>` (en-US) | | | `spellcheck` | Global attribute | 指示為該元素的拼字檢查是否允許。 | | `scope` | `<th>` (en-US) | | | `scoped` | `<style>` (en-US) | | | `seamless` | `<iframe>` (en-US) | | | `selected` | `<option>` (en-US) | 定義一個值將被選擇到上載頁面中。 | | `shape` | `<a>` (en-US)、`<area>` (en-US) | | | `size` | `<input>` (en-US)、`<select>` (en-US) | 定義元素的寬度 (以 pixel 為單位) 。如果該元素之類型的屬性是文本或是密碼,那麼它就是字元的數目。 | | `sizes` | `<link>` (en-US) | | | `span` | `<col>` (en-US)、`<colgroup>` (en-US) | | | `src` | `<audio>` (en-US)、`<embed>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<input>` (en-US)、`<script>`、`<source>` (en-US)、`<track>` (en-US)、`<video>` (en-US) | 可嵌入內容的網址。 | | `srcdoc` | `<iframe>` (en-US) | | | `srclang` | `<track>` (en-US) | | | `srcset` | `<img>` (en-US) | | | `start` | `<ol>` (en-US) | 如果第一個數字不是 1 的話,則定義該數。 | | `step` | `<input>` (en-US) | | | `style` | Global attribute | 定義多載先前的樣式設定之 CSS 樣式。 | | `summary` | `<table>` | | | `tabindex` | Global attribute | 多載瀏覽器的預設頁面標籤之順序並且遵守指定的那個。 | | `target` | `<a>` (en-US)、`<area>` (en-US)、`<base>` (en-US)、`<form>` (en-US) | | | `title` | Global attribute | 當滑鼠標停在元素時,文本會顯示在工具提示中。 | | `type` | `<button>` (en-US)、`<input>` (en-US)、`<command>`、`<embed>` (en-US)、`<object>` (en-US)、`<script>`、`<source>` (en-US)、`<style>` (en-US)、`<menu>` (en-US) | 定義元素的類型。 | | `usemap` | `<img>` (en-US)、`<input>` (en-US)、`<object>` (en-US) | | | `value` | `<button>` (en-US)、`<option>` (en-US)、`<input>` (en-US)、`<li>` (en-US)、`<meter>` (en-US)、`<progress>` (en-US)、`<param>` (en-US) | 定義將顯示在加載頁面上元素的預設值。 | | `width` | `<canvas>`、`<embed>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<input>` (en-US)、`<object>` (en-US)、`<video>` (en-US) | 注意 : 在有些情況中,例如 `<div>`,這是傳統的屬性,而 CSS `width` 特性應當被使用。在其他的情況中,例如 `<canvas>` ,寬度必須用該屬性來指定。 | | `wrap` | `<textarea>` (en-US) | 指定文章是否要被掩飾。 | | `border` | `<img>` (en-US)、`<object>` (en-US)、`<table>` | 邊界寬度。注意:這是一個傳統的屬性。請利用 CSS `border` (en-US) 特性。 | | `buffered` | `<audio>` (en-US)、`<video>` (en-US) | 包含被緩衝之媒體的時間範圍。 | | `charset` | `<meta>` (en-US)、`<script>` | 聲明頁面或腳本的字元編碼。 | | `checked` | `<command>`、`<input>` (en-US) | 指定在加載頁面上的元素是否要被檢查。 | | `cite` | `<blockquote>`、`<del>` (en-US)、`<ins>` (en-US)、`<q>` | 包含一個 URL,用來指出引用或是改變的來源地址。 | | `class` | Global attribute | 經常使用共同屬性和 CSS 一起設計元素。 | | `code` | `<applet>` | 指明被加載與執行的 applet 類別文件之 URL。 | | `codebase` | `<applet>` | This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored. | | `color` | `<basefont>` (en-US)、`<font>`、`<hr>` | 該屬性使用命名顏色或十六進制 #RRGGBB 格式來設置文本顏色。注意:這是一個傳統的屬性。請使用 CSS `color` (en-US) 特性。 | | `cols` | `<textarea>` (en-US) | 定義在一個 textarea 中有多少欄位。 | | `colspan` | `<td>` (en-US)、`<th>` (en-US) | colspan 屬性定義一個單元格之欄位的數量。 | | `content` | `<meta>` (en-US) | 一個有關於 `http-equiv` 或是根據上下文 `name` 的值 。 | | `contenteditable` | Global attribute | 指定元素的內容是否可以被編輯。 | | `contextmenu` | Global attribute | 定義將作為元素上下文選項單的 `<menu>` (en-US) 元素之 ID。 | | `controls` | `<audio>` (en-US)、`<video>` (en-US) | 指定瀏覽器是否應該顯示錄放控制給使用者。 | | `coords` | `<area>` (en-US) | 一組值指明熱點區域的座標。 | | `data` | `<object>` (en-US) | 指明 URL 的資源。 | | `data-*` | Global attribute | 讓你可以將自行定義屬性附加在 HTML 元素上。 | | `datetime` | `<del>` (en-US)、`<ins>` (en-US)、`<time>` | 指定元素所相關的日期與時間。 | | `default` | `<track>` (en-US) | 指定 track 應被啟用,除非使用者的偏好表示不同。 | | `defer` | `<script>` | 指定該頁面被瀏覽完後腳本應被執行。 | | `dir` | Global attribute | 定義文章的方向。被允許的值有 ltr (Left-To-Right) 或 rtl (Right-To-Left)。 | | `dirname` | `<input>` (en-US)、`<textarea>` (en-US) | | | `disabled` | `<button>` (en-US)、`<command>`、`<fieldset>` (en-US)、`<input>` (en-US)、`<optgroup>` (en-US)、`<option>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US) | 指名使用者是否可以與元素互動。 | | `download` | `<a>` (en-US)、`<area>` (en-US) | 指定該超連結是用於下載的資源。 | | `draggable` | Global attribute | 定義元素是否可以拖曳。 | | `dropzone` | Global attribute | 指定該元素接受它內容的滑鼠落下物。 | | `enctype` | `<form>` (en-US) | 當方法為 POST 的時候,定義格式日期的內容類型。 | | `for` | `<label>` (en-US)、`<output>` (en-US) | 描述屬於這一個的元素。 | | `form` | `<button>` (en-US)、`<fieldset>` (en-US)、`<input>` (en-US)、`<label>` (en-US)、`<meter>` (en-US)、`<object>` (en-US)、`<output>` (en-US)、`<progress>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US) | 指定元素之所有者的格式。 | | `formaction` | `<input>` (en-US)、`<button>` (en-US) | 指定元素的作用,多載的動作被定義在 `<form>` (en-US)。 | | `headers` | `<td>` (en-US)、`<th>` (en-US) | 對適用於該元素的 | 元素之 ID。 | | `height` | `<canvas>`、`<embed>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<input>` (en-US)、`<object>` (en-US)、`<video>` (en-US) | 注意:在有些情況中,例如 `<div>`,這是傳統的屬性,而 CSS `height` 特性應當被使用。在其他的情況中,例如 `<canvas>`,高度必須用該屬性來指定。 | | `accept` | `<form>` (en-US)、`<input>` (en-US) | 伺服器接受的類型之列表,通常是文件類型。 | | `accept-charset` | `<form>` (en-US) | 支持字元集的列表。 | | `accesskey` | Global attribute | 定義鍵盤快捷鍵來啟動或添加焦點到該元素。 | | `action` | `<form>` (en-US) | 一個程序處理經由該格式提交信息的 URI。 | | `align` | `<applet>`、`<caption>` (en-US)、`<col>` (en-US)、`<colgroup>` (en-US)、`<hr>`、`<iframe>` (en-US)、`<img>` (en-US)、`<table>`、`<tbody>` (en-US)、`<td>` (en-US)、`<tfoot>` (en-US) 、`<th>` (en-US)、`<thead>` (en-US)、`<tr>` (en-US) | 指定元素的水平對齊方式。 | | `alt` | `<applet>`、`<area>` (en-US)、`<img>` (en-US)、`<input>` (en-US) | 在圖像無法顯示的情況下,顯示代替文本。 | | `async` | `<script>` | 指定該腳本應該被不同步得執行。 | | `autocomplete` | `<form>` (en-US)、`<input>` (en-US) | 指定是否以該格式控制,可以在默認情況下由瀏覽器自動完成其值。 | | `autofocus` | `<button>` (en-US)、`<input>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US) | 該元素應該在頁面加載後自動焦距。 | | `autoplay` | `<audio>` (en-US)、`<video>` (en-US) | 音頻或視頻應該越早撥放越好。 | | `autosave` | `<input>` (en-US) | 上一個值應該持續存在到跨頁面加載的可選值之下拉列表中。 | | `bgcolor` | `<body>` (en-US)、`<col>` (en-US)、`<colgroup>` (en-US)、`<marquee>`、`<table>`、`<tbody>` (en-US)、`<tfoot>` (en-US)、`<td>` (en-US)、`<th>` (en-US)、`<tr>` (en-US) | 元素的背景顏色。注意:這是一個傳統的屬性。請使用 CSS `background-color` 特性。 | 內容與 IDL 屬性 ---------- 在 HTML 中,大部分的屬性有兩種面向:**內容屬性**與 **IDL 屬性**。 內容屬性是你可以從內容中設定的屬性 (HTML 程式碼) 而且你可以藉由 `element.setAttribute()` (en-US) 或是 `element.getAttribute()` (en-US) 來設定它或得到它。內容屬性永遠都是字串,即便我們所期望的值是一個整數。舉例來說,假設今天要用內容屬性去設定一個 `<input>` (en-US) 元素的最大長度是 42,你必須在該元素上呼叫 setAttribute("maxlength", "42")。 IDL 屬性也被稱為 JavaScript 特性。你可以使用 JavaScript 特性的 element.foo 以閱讀或是設定這些屬性。當你要得到 IDL 屬性時,它總是要使用 (但可能改變) 基本的內容屬性以返回值,而當你要設定 IDL 屬性時,它需要儲存資料在內容屬性中。換句話說,IDL 屬性在本質上反映了內容屬性。 在大部分的時間中,當 IDL 屬性真正被使用時,將會返回它們的值。舉例而言,`<input>` (en-US) 元素的預設型態是 "text",所以如果你設定 input.type="foobar",<input> 元素一樣是 text 的型態 (在外觀和行為上而言),但是 "type" 內容屬性的值將會變成 "foobar"。然而,IDL 屬性的型態將會回傳 "text" 字串。 IDL 屬性並非永遠的字串 ; 舉例來說,input.maxlength 便是一個數字(型態為 signed long)。當使用 IDL 屬性,你會閱讀或是設定所需的型態,而當你設定 input.maxlength 時,它總是回傳一個數字,因為它正需要一個數字。如果你傳入別的型態,它會依照標準 JavaScript 型態轉換規則,將傳入值轉成一個數字。 IDL 屬性可以 反應其他型態,例如 unsigned long、URLs、booleans,等等。不幸的是,並沒有明確的規則來規範,而且與 IDL 屬性行為相對應的內容屬性連結中,也沒有取決於該屬性的方式。在大部分的時間裡,它會遵守 規範中所制定的規則,但有時候它並不會。HTML 規範嘗試讓它變得容易使用,但由於各種原因 (大多是因為歷史),有些屬性表現得很奇怪 (舉例來說,select.size),而你應該詳細閱讀規範以了解各個屬性的行為。 另請參見 ---- * HTML 元素 (en-US)
內容類型 - HTML:超文本標記語言
內容類型 ==== 每個 HTML 元素都要遵從該元素可擁有何種內容規則,這些規則被歸為幾種常用的內容模型(content model)。每個 HTML 元素都屬於零個、一個、或數個內容的模型,所有元素內容的設置規則都要遵從 HTML 一致性文件。 內容類型有三種類型: * 主要內容類型(Main content categories)描述了許多元素共享的常見內容規則(content rule)。 * 表單相關內容類型(Form-related content categories)描述了表單相關元素的內容規則。 * 特別內容類型(Specific content categories) 描述了只有少數元素共享的內容規則,有時甚至只有特定上下文。 ![Content_categories_venn.png](/zh-TW/docs/Web/HTML/Content_categories/content_categories_venn.png) 主要內容類型 ------ ### 資訊元內容(Metadata content) 屬於*元資訊內容*類型的元素修飾該文件其餘部分的陳述或行為、與其他文件建立連結、或是傳達其他*外來*(out of band)訊息。 屬於這個類型的元素有 `<base>` (en-US)、 已棄用 `<command>`、`<link>` (en-US)、`<meta>` (en-US)、`<noscript>`、`<script>`、`<style>` (en-US) 與 `<title>` ### 流內容(Flow content) 屬於流內容的元素通常含有文字或嵌入內容。它們是:`<a>` (en-US)、`<abbr>` (en-US)、`<address>` (en-US)、`<article>` (en-US)、`<aside>` (en-US)、`<audio>` (en-US)、`<b>` (en-US),`<bdo>` (en-US)、`<bdi>` (en-US)、`<blockquote>`、`<br>`、`<button>` (en-US)、`<canvas>`、`<cite>` (en-US)、`<code>`、 已棄用 `<command>`、`<data>` (en-US)、`<datalist>` (en-US)、`<del>` (en-US)、`<details>` (en-US)、`<dfn>` (en-US)、`<div>`、`<dl>` (en-US)、`<em>` (en-US)、`<embed>` (en-US)、`<fieldset>` (en-US)、`<figure>` (en-US)、`<footer>` (en-US)、`<form>` (en-US)、`<h1>` (en-US)、`<h2>` (en-US)、`<h3>` (en-US)、`<h4>` (en-US)、`<h5>` (en-US)、`<h6>` (en-US)、`<header>` (en-US)、`<hgroup>` (en-US)、`<hr>`、`<i>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<input>` (en-US)、`<ins>` (en-US)、`<kbd>` (en-US)、`<label>` (en-US)、`<main>` (en-US)、`<map>` (en-US)、`<mark>` (en-US)、`<math> (en-US)`、`<menu>` (en-US)、`<meter>` (en-US)、`<nav>`、`<noscript>`、`<object>` (en-US)、`<ol>` (en-US)、`<output>` (en-US)、`<p>` (en-US)、`<pre>` (en-US)、`<progress>` (en-US)、`<q>`、`<ruby>`、`<s>` (en-US)、`<samp>` (en-US)、`<script>`、`<section>` (en-US)、`<select>` (en-US)、`<small>` (en-US)、`<span>` (en-US)、`<strong>` (en-US)、`<sub>` (en-US)、`<sup>` (en-US)、`<svg>` (en-US)、`<table>`、`<template>`、`<textarea>` (en-US)、`<time>`、`<ul>` (en-US)、`<var>` (en-US)、`<video>` (en-US)、`<wbr>` (en-US) 還有文字。 在滿足特定條件下,某些元素也屬這個類型: * `<area>` (en-US),如果它是 `<map>` (en-US) 元素的後代。 * `<link>` (en-US),如果**itemprop** (en-US) 屬性存在。 * `<meta>` (en-US),如果**itemprop** (en-US) 屬性存在。 * `<style>` (en-US),如果 `scoped` (en-US) 屬性存在。 ### 章節型內容(Sectioning content) 屬於章節型內容模型的元素會在該大綱裡面創立章節,這個章節會定義`<header>` (en-US)、`<footer>` (en-US)、還有heading content的範圍。 屬於這個類型的元素有`<article>` (en-US)、`<aside>` (en-US)、`<nav>`還有`<section>` (en-US)。 **備註:** 不要把這個內容模型,和把內容與常規大綱隔開的 sectioning root 類別搞混。 ### 標題型內容(Heading content) 標題型內容定義了章節的標題,不論該章節由明確的章節型內容元素標記、抑或由標題本身隱式定義。 屬於這個類型的元素有`<h1>` (en-US)、`<h2>` (en-US)、`<h3>` (en-US), `<h4>` (en-US)、`<h5>` (en-US)、`<h6>` (en-US)還有`<hgroup>` (en-US). **備註:** 儘管 `<header>` (en-US) 可能含有某些標題型內容,但它本身並不是。 ### 段落型內容(Phrasing content) 段落型內容定義了文字、還有它包含的標記。Runs of phrasing content make up paragraphs. 屬於這個類型的元素有`<abbr>` (en-US)、`<audio>` (en-US)、`<b>` (en-US)、`<bdo>` (en-US)、`<br>`、`<button>` (en-US)、`<canvas>`、`<cite>` (en-US)、`<code>`、 已棄用 `<command>`、`<datalist>` (en-US)、`<dfn>` (en-US)、`<em>` (en-US)、`<embed>` (en-US)、`<i>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<input>` (en-US)、`<kbd>` (en-US)、`<label>` (en-US)、`<mark>` (en-US)、`<math> (en-US)`、`<meter>` (en-US)、`<noscript>`、`<object>` (en-US)、`<output>` (en-US)、`<progress>` (en-US)、`<q>`、`<ruby>`、`<samp>` (en-US)、`<script>`、`<select>` (en-US)、`<small>` (en-US)、`<span>` (en-US)、`<strong>` (en-US)、`<sub>` (en-US)、`<sup>` (en-US)、`<svg>` (en-US)、`<textarea>` (en-US)、`<time>`、`<var>` (en-US)、`<video>` (en-US)、`<wbr>` (en-US)以及空白字符在內的純文本。 在滿足特定條件下,某些元素也屬這個類型: * `<a>` (en-US),如果它只包含段落型內容。 * `<area>` (en-US),如果它是 `<map>` (en-US) 元素的後代。 * `<del>` (en-US),如果它只包含段落型內容。 * `<ins>` (en-US), 如果它只包含段落型內容。 * `<link>` (en-US), 如果 **itemprop** (en-US) 屬性存在。 * `<map>` (en-US), 如果它只包含段落型內容。 * `<meta>` (en-US), 如果 **itemprop** (en-US) 屬性存在。 ### 嵌入型內容(Embedded content) 嵌入型內容從其他標記語言或文件命名空間,導入資源或插入內容。 屬於這個類型的元素有`<audio>` (en-US)、`<canvas>`、`<embed>` (en-US)、`<iframe>` (en-US)、`<img>` (en-US)、`<math> (en-US)`、`<object>` (en-US)、`<svg>` (en-US)、`<video>` (en-US)。 ### 互動型內容(Interactive content) 互動型內容包含專為用戶互動設計的元素。屬於這個類型的元素有 `<a>` (en-US)、`<button>` (en-US)、`<details>` (en-US)、`<embed>` (en-US)、`<iframe>` (en-US)、`<label>` (en-US)、`<select>` (en-US) 還有 `<textarea>` (en-US)。 在滿足特定條件下,某些元素也屬這個類型: * `<audio>` (en-US),如果 `controls` (en-US) 元素存在。 * `<img>` (en-US),如果 `usemap` (en-US) 元素存在。 * `<input>` (en-US),如果 `type` (en-US) 元素不是隱藏狀態。 * `<menu>` (en-US),如果 `type` (en-US) 元素處於 toolbar 狀態。 * `<object>` (en-US),如果 `usemap` (en-US) 元素存在。 * `<video>` (en-US),如果 `controls` (en-US) 元素存在。 ### 捫及內容(Palpable content) 不是空白或隱藏的內容稱為捫及。屬於流內容或是 Phrasing content 模型的元素最少要有一個捫及的節點。 ### 表單相關內容(Form-associated content) 表單相關內容包含了由 **form** 屬性顯露的 form owner 元素。form owner 是本身包含於 `<form>` (en-US)、或 id 由 **form** 屬性指定的元素。 * `<button>` (en-US) * `<fieldset>` (en-US) * `<input>` (en-US) * `<label>` (en-US) * `<meter>` (en-US) * `<object>` (en-US) * `<output>` (en-US) * `<progress>` (en-US) * `<select>` (en-US) * `<textarea>` (en-US) 本類型包含某些子類別: listed Elements that are listed in the form.elements (en-US) and fieldset.elements IDL collections. Contains `<button>` (en-US), `<fieldset>` (en-US), `<input>` (en-US), `<object>` (en-US), `<output>` (en-US), `<select>` (en-US), and `<textarea>` (en-US). labelable 與元素 `<label>` (en-US) 相關的元素。包含 `<button>` (en-US)、`<input>` (en-US)、`<meter>` (en-US)、`<output>` (en-US)、`<progress>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US)。 submittable 用在建構送出時,資料就設定好的表單元素。包含 `<button>` (en-US)、`<input>` (en-US)、`<object>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US)。 resettable 當表單重設時會受影響的元素。包含 `<button>` (en-US)、`<input>` (en-US)、`<output>` (en-US)、`<select>` (en-US)、`<textarea>` (en-US)。 透明內容模型(Transparent content model) --------------------------------- 如果一個元素是透明內容模型,then its contents must be structured such that they would be valid HTML 5,就算該透明元素被移除、並由子元素取代。 例如,`<del>` (en-US) 與 `<ins>` (en-US) 元素都是透明的: ``` <p>我們認為下面這些真理是<del><em>神聖不可否認</em></del><ins>不言而喻的。</ins></p> ``` 這果這些元素被刪掉的話,這個分段依然在 HTML 有效(if not correct English) ``` <p>我們認為下面這些真理是<em>神聖不可否認</em>不言而喻的。</p> ``` 其他內容模型 ------ 章節根(Sectioning root)
<script> - HTML:超文本標記語言
<script> ======== **HTML `<script>` 元素**能嵌入或引用要執行的程式碼。最常見的用途是嵌入或引用 JavaScript 程式碼。`<script>` 元素也能執行其他語言,例如 WebGL (en-US) 的 GLSL shader 程式語言。 | 內容類型 | 元資料內容、流型內容、Phrasing content. | | --- | --- | | 允許的內容 | 動態腳本如 `text/javascript`. | | 標籤省略 | None, both the starting and ending tag are mandatory. | | 允許的父元素 | 任何可接受 元資料內容或 phrasing content 的元素。 | | 允許的 ARIA role | None | | DOM 介面 | `HTMLScriptElement` (en-US) | 屬性 -- 此元素包含了全域屬性 (en-US)。 `async` 這個布林屬性告訴瀏覽器說:如果可以,就以非同步的方法執行腳本。 **警告:** 如果沒有 `src` 屬性的話,就不能用這個屬性(例如行內腳本):在這種情況下,它將失去作用。 `async` 在 HTML 解析時,瀏覽器通常會假定最壞的情況,並同步地載入腳本(例如 `async=false`)。 動態插入的腳本(例如 `document.createElement`)一般來說是非同步執行的。因此,如果設定同步的話(腳本按照被插入的順序執行),會被設為 `async=false`。 請參見相容性註解的瀏覽器支援備註。另請參見 Async scripts for asm.js (en-US)。 `crossorigin` 針對沒有通過標準 CORS (en-US) 的一般 `script` 元素,會把最少的資訊傳給 `window.onerror` (en-US)。若要允許另一個域名站點的靜態內容,列出錯誤訊息,請使用此屬性。請參見 CORS settings attributes (en-US) 以以取得對其有效參數的,更具描述性的解釋。 `defer` 設置此 Boolean attribute 是為了指示瀏覽器,腳本應在 document 解析後,但在觸發 `DOMContentLoaded` (en-US) 之前被執行。具有 `defer` 屬性的腳本將阻止觸發 `DOMContentLoaded` 事件,直到腳本 load 完成並且 finished evaluating。 **警告:** 如果沒有 `src` 屬性的話,就不能用這個屬性(例如行內腳本):在這種情況下,它將失去作用。The `defer` attribute has no effect on module script (en-US) — they defer by default. `fetchpriority` Scripts with the `defer` attribute will execute in the order in which they appear in the document.This attribute allows the elimination of **parser-blocking JavaScript** where the browser would have to load and evaluate scripts before continuing to parse. `async` has a similar effect in this case. `integrity` This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See Subresource Integrity (en-US). `nomodule` 這個布林屬性,會要求支援 ES2015 modules 的瀏覽器,不執行裡面的程式。這能用來給不支援 JavaScript 模組的老舊瀏覽器,提供用於向下支援的服務。 `nonce` A cryptographic nonce (number used once) to whitelist inline scripts in a script-src Content-Security-Policy (en-US). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. `src` 此屬性指定外部程式的 URI,可以用來取代直接在文件內中嵌入腳本。 **警告:** 如果 `script` 元素有指定 `src` 屬性的話,標籤內就不能有嵌入的腳本。 `text` Like the `textContent` attribute, this attribute sets the text content of the element. Unlike the `textContent` attribute, however, this attribute is evaluated as executable code after the node is inserted into the DOM. `type` 此屬性指定程式碼應該表示的類型。此屬性的值會屬於以下類別之一:**省略或 JavaScript MIME 類型**:針對相容 HTML5 的瀏覽器來說,元素內會執行 JavaScript。HTML5 規範敦促作者省略此屬性,不需要寫冗長的 MIME 類型。在早期的瀏覽器中,這確定了嵌入或引入(透過 `src` 屬性)腳本的語言。JavaScript MIME 類型有列在規範內 (en-US)。 * **`module`**:針對相容 HTML5 的瀏覽器來說,這段程式碼會當成 JavaScript 模組(module)。腳本內容的處理不受 `charset` 與 `defer` 屬性影響。針對 `module` 的資訊,請參閱 ES6 in Depth: Modules。在使用 `module` 關鍵字時,程式碼的行為會有所不同。 * **其他值**:嵌入的內容會被當成一段不給瀏覽器執行的資料塊(data block)。開發者應當使用非 JavaScript 的有效 MIME 類型,以標明資料塊。`src` 屬性也將被忽略。 **備註:** 在 Firefox 你可以在 `<script>` 元素的 `type` 屬性,透過標明非標準參數 `version`,指定要使用的 JavaScript 版本:例如說 `type="application/javascript;version=1.8"`。這個功能在 Firefox 59 移除了(請參見 Firefox bug 1428745)。 ### 棄用屬性 `language` 已棄用 如同 `type` 屬性,此屬性指定正在使用的腳本語言。但與 `type` 屬性不同,此屬性的可用值從未標準化。應當使用 `type` 屬性。 註解 -- Scripts without `async` or `defer` attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page. The script should be served with the `text/javascript` MIME type, but browsers are lenient and only block them if the script is served with an image type (`image/*`); a video type (`video/*`); an audio (`audio/*`) type; or `text/csv`. If the script is blocked, an `error` (en-US) is sent to the element, if not a `load` (en-US) event is sent. 示例 -- ### 基本 以下示例展示如何在 HTML4 與 HTML5 使用 `<script>` 屬性。 ```html <!-- HTML4 與 (x)HTML --> <script type="text/javascript" src="javascript.js"></script> <!-- HTML5 --> <script src="javascript.js"></script> ``` ### 模組的向下支援方案 有針對 type 屬性支援 module(模組)的瀏覽器,會忽略 nomodule 屬性的程式碼。這能讓那些不支援模組的瀏覽器,提供替代的使用方法。 ```js <script type="module" src="main.mjs"></script> <script nomodule src="fallback.js"></script> ``` 規範 -- | Specification | | --- | | HTML Standard # the-script-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相容性註解 ----- In older browsers that don't support the `async` attribute, parser-inserted scripts block the parser; script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4 Firefox. In Firefox 4, the `async` DOM property defaults to `true` for script-created scripts, so the default behaviour matches the behaviour of IE and WebKit. To request script-inserted external scripts be executed in the insertion order in browsers where the `document.createElement("script").async` evaluates to `true` (such as Firefox 4), set `.async=false` on the scripts you want to maintain order. **警告:** Never call `document.write()` from an async script. In Firefox 3.6, calling `document.write()` has an unpredictable effect. In Firefox 4, calling `document.write()` from an async script has no effect (other than printing a warning to the error console). 參見 -- * `document.currentScript` (en-US) * Ryan Grove's <script> and <link> node event compatibility chart
<ruby> - HTML:超文本標記語言
<ruby> ====== **HTML `<ruby>` 元素**的意思是旁註標記。旁註標記用於標示東亞文字的發音。 嘗試一下 ---- | 內容類型 | 流內容、段落型內容、捫及內容 | | --- | --- | | 允許內容 | 段落型內容 | | 標籤省略 | None, both the starting and ending tag are mandatory. | | 允許父元素 | Any element that accepts phrasing content (en-US) | | DOM 介面 | `HTMLElement` (en-US) | 屬性 -- 這個元素只支援全域屬性 (en-US)。 範例 -- ### 範例一:字 ```html <ruby> 漢 <rp>(</rp><rt>Kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> ``` ### 範例二:詞 ```html <ruby> 明日 <rp>(</rp><rt>Ashita</rt><rp>)</rp> </ruby> ``` 規範 -- | Specification | | --- | | HTML Standard # the-ruby-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參閱 -- * `<rt>` (en-US) * `<rp>` (en-US) * `<rb>` (en-US) * `<rtc>` (en-US) * `<rbc>` * `text-transform` (en-US): full-size-kana
<head> - HTML:超文本標記語言
<head> ====== HTML 中的 **`<head>`** 元素包含有關文件的機器可讀信息(後設資料),例如 標題、腳本、樣式表 (en-US)。 **備註:**`<head>` 主要保存用於機器處理的訊息,而不是人類可讀的訊息。對於人類可見的訊息,例如頂級標題和列出的作者,請參見 `<header>` (en-US) 元素。 屬性 -- 這個元件屬性含有全域屬性 (en-US)。 範例 -- ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>Document title</title> </head> </html> ``` 技術摘要 ---- | | | | --- | --- | | 內容類型 | 無 | | 允許內容 | 如果文件是一個 `<iframe>` (en-US) `srcdoc` (en-US) 文件,或者如果標題信息來自於更高級的協議(像是 HTML 電子郵件的主題行),則應包含零個或多個元素的後設資料內容。 否則,必須包含一個或多個元素的後設資料內容,其中確實包括一個 `<title>` 元素。 | | 標籤省略 | 如果 `<head>` 元素內的第一個內容是一個元素,則開起標籤可以省略。如果跟在 `<head>` 元素後面的第一個內容不是空格字符或註釋,則關閉標籤可以省略。 | | 允許的父元素 | 作為 `<html>` (en-US) 元素的第一個子元素。 | | 允許的 ARIA 角色 | 沒有允許的 `role` | | DOM 介面 | `HTMLHeadElement` (en-US) | 規範 -- | Specification | | --- | | HTML Standard # the-head-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 可以使用在 `<head>` 中的元素: + `<title>` + `<base>` (en-US) + `<link>` (en-US) + `<style>` (en-US) + `<meta>` (en-US) + `<script>` + `<noscript>` + `<template>`
<marquee>:捲動元素(已過時) - HTML:超文本標記語言
<marquee>:捲動元素(已過時) =================== **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 HTML `<marquee>` 元素用作插入一段文字的捲動區域。你可以透過屬性,控制文字在到達邊緣後的應對動作。 | | | | --- | --- | | DOM 介面 | `HTMLMarqueeElement` (en-US) | 屬性 -- `behavior` 設定文字如何在 marquee 內捲動。可用值為 `scroll`、`slide`、`alternate`。若無指定,預設值為 `scroll`。 `bgcolor` 透過色彩名或十六進位值指定背景顏色。 `direction` 設定 marquee 內的捲動方向。可用值為 `left`、`right`、`up`、`down`。若無指定,預設值為 `left`。 `height` 設定像素或百分比高度。 `hspace` 設定橫向外邊(horizontal margin) `loop` 設定 marquee 捲動的次數。若無指定,預設值為 -1,意思是的 marquee 將持續捲動。 `scrollamount` 以像素為單位,設定捲動的間隔量。預設值為 6。 `scrolldelay` 設定每次捲動時之間間隔的毫秒。預設值為 85。請注意,除非指定了 `truespeed`,否則小於 60 的數字會被忽略,並值使用 60。 `truespeed` `scrolldelay` 預設上會忽略低於 60 的值。但如果有 `truespeed` 的話,就不會忽略此值。 `vspace` 以像素或百分比值設置垂直邊距。 `width` 設置以像素或百分比值為單位的寬度。 事件處理器 ----- `onbounce` marquee 滾動到結尾時觸發。只能在 behavior 屬性設置為 `alternate` 時觸發。 `onfinish` marquee 完成 loop 屬性的設定值時觸發。只能在 loop 屬性設為大於 0 的數字時觸發。 `onstart` marquee 開始捲動時觸發。 方法 -- start() 開始 marquee 的捲動 stop() 停止 marquee 的捲動 示例 -- ```html <marquee>This text will scroll from right to left</marquee> <marquee direction="up">This text will scroll from bottom to top</marquee> <marquee direction="down" width="250" height="200" behavior="alternate" style="border:solid"> <marquee behavior="alternate">This text will bounce</marquee> </marquee> ``` 規範 -- | Specification | | --- | | HTML Standard # the-marquee-element-2 | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `HTMLMarqueeElement` (en-US)
<picture>: The Picture element - HTML:超文本標記語言
<picture>: The Picture element ============================== **HTML `<picture>` 元素** 包含了零或零以上個 `<source>` (en-US) 元素以及一個 `<img>` (en-US) 元素,以為不同顯示器/裝置提供同張圖片的不同版本。 瀏覽器將會考慮每個 `<source>` 元素,並且在其中選出最適當的選項。如果沒有找到最適當的選項——或是瀏覽器不支援 `<picture>` 元素——則 `<img>` 屬性的 URL 會被選擇。被選擇的圖片將會在 `<img>` 元素存在的位置顯示。 嘗試一下 ---- 為了決定載入哪一個 URL,user agent (en-US) 會檢視每一個 `<source>` 的 `srcset` (en-US)、`media` (en-US) 以及 `type` (en-US) 屬性,以選出最適合當前版面以及顯示裝置支援度的圖片。 `<img>` 有兩個作用: 1. 它描述了該圖片的尺寸等屬性以及呈現(presentation)。 2. 在所有列出的 `<source>` 都不能提供可用圖片的情況下的 fallback。 `<picture>` 的常見使用案例: * **圖像方向(art direction):** 根據不同的 `media` 狀況裁切或調整圖片(例如在較小的螢幕上,載入原本有複雜細節圖片的較簡單版本圖片) * \*\*提供替代的圖片格式:\*\*以應對某些特定格式不被支援的情況 * \*\*節省頻寬並加速頁面載入速度:\*\*透過針對觀看者的裝置載入最適當的圖片做到這點 如果是要為高 DPI (Retina)螢幕提供圖片的高解析度版本時,可改在使用 `<img>` 上使用 `srcset` (en-US) 屬性。這會讓瀏覽器在 data-saving 模式選擇低解析度的版本,這樣你就不用特地指定 `media` 條件。 | Content categories | Flow content, phrasing content, embedded content | | --- | --- | | Permitted content | Zero or more `<source>` (en-US) elements, followed by one `<img>` (en-US) element, optionally intermixed with script-supporting elements. | | Tag omission | None, both the starting and ending tag are mandatory. | | Permitted parents | Any element that allows embedded content. | | Implicit ARIA role | No corresponding role | | Permitted ARIA roles | No `role` permitted | | DOM interface | `HTMLPictureElement` (en-US) | 屬性 -- 此元素只包含 global attributes (en-US). 用法筆記 ---- 你可以使用 `object-position` (en-US) 屬性來在元素的 frame 內調整圖片位置,也可以用 `object-fit` (en-US) 屬性控制圖片在 frame 內如何調整大小。 **備註:** 在子元素 `<img>` 上使用這些屬性,而不是 `<picture>` 元素. 範例 -- 以下例子示範如何根據 `<source>` (en-US) 元素不同的屬性設定選擇 `<picture>` 中的不同圖片。 ### media 屬性 `media` 屬性指定特定的媒體類型(跟 media query 很像),讓 user agent 可對每個 `<source>` (en-US) 元素作出判斷。 如果 `<source>` (en-US) 的指定媒體類型被判斷為 `false` ,則瀏覽器會跳過它,並繼續判斷 `<picture>` 中的下個元素。 ```html <picture> <source srcset="mdn-logo-wide.png" media="(min-width: 600px)" /> <img src="mdn-logo-narrow.png" alt="MDN" /> </picture> ``` ### srcset 屬性 `srcset` (en-US) 屬性用來提供根據大小區分的可能圖片清單。 它是由逗號分隔的圖片描述句清單組成的。每一個圖片描述句是由該圖片的 URL 以及以下描述組成(擇一): * 寬度,結尾為 `w` (例如 `300w`); *或是* * 像素密度,結尾為 `x` (例如 `2x`),以為高 DPI 螢幕提供高解析度圖片 ```html <picture> <source srcset="logo-768.png 768w, logo-768-1.5x.png 1.5x" /> <source srcset="logo-480.png, logo-480-2x.png 2x" /> <img src="logo-320.png" alt="logo" /> </picture> ``` ### type 屬性 `type` 屬性為 `<source>` (en-US) 元素中 `srcset` 屬性的資源 URL 指定 MIME type (en-US) 。如果 user agent 不支援該 type 的話,此 `<source>` (en-US) 元素會被略過。 ```html <picture> <source srcset="logo.webp" type="image/webp" /> <img src="logo.png" alt="logo" /> </picture> ``` 規格 -- | Specification | | --- | | HTML Standard # the-picture-element | 瀏覽器支援度 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資源 ---- * `<img>` (en-US) 元素 * `<source>` (en-US) 元素 * 在圖片的 frame 中調整其大小與位置: `object-position` (en-US) and `object-fit` (en-US) * 圖片檔案類型與格式指南 (en-US)
<br>(斷行元素) - HTML:超文本標記語言
<br>(斷行元素) ========== **HTML `<br>` 元素**會產生文字的斷行(carriage-return、CR 或是確認鍵)。此元素主要用於斷行有所意義的時候,像是寫詩或寫住址。 嘗試一下 ---- 如上所示,`<br>` 元素會在需要斷行的時候出現。在 `<br>` 之後的文字會從文字區域的下一行出現。 **備註:** 不要用 `<br>` 建立段落間距:這種情況下要用 `<p>` (en-US) 把它們包起來,並使用 CSS `margin` (en-US) 屬性控制間距大小。 屬性 -- 這個元件屬性含有全域屬性 (en-US)。 ### 棄用屬性 `clear` 指示中斷後下一行的開始位置。 使用 CSS 樣式化 ---------- `<br>` 元素有一個定義明確的用途:在文字區塊裡面建立斷行。因此它本身沒有尺寸或視覺輸出,基本上你做不了任何樣式化。 你可以給 `<br>` 元素設置 `margin` (en-US) 以增加文字之間的斷行大小,但這並不是正確的作法:你應該用 `line-height` (en-US) 屬性做這件事情。 示例 -- ```html Mozilla Foundation<br /> 1981 Landings Drive<br /> Building K<br /> Mountain View, CA 94043-0801<br /> USA ``` 以上 HTML 將顯示 無障礙議題 ----- 使用 `<br>` 元素*分段*不只作法不佳,對於使用輔具的人來說,也會是有問題的。螢幕閱讀器會念出該元素,但 `<br>` 裡面的內容是念不出來的。對於使用螢幕閱讀器的人來說,這可能是困惑與沮喪的體驗。 請使用 `<p>` 元素搭配 CSS 屬性如 `margin` (en-US) 來控制間距大小。 技術摘要 ---- | 內容類型 (en-US) | 流型內容 (en-US)、段落型內容 (en-US)。 | | --- | --- | | 允許內容 | 無,這是個空元素. | | 標籤省略 | 絕對要有開啟標籤,也絕不能關閉標籤。在 XHTML 文件內,要把這個元素寫成 `<br />`. | | 允許父元素 | 任何接受段落型內容 (en-US)的元素 | | 允許的 ARIA roles | 所有 | | DOM 介面 | `HTMLBRElement` (en-US) | 規範 -- | Specification | | --- | | HTML Standard # the-br-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `<address>` (en-US) 元素 * `<p>` (en-US) 元素 * `<wbr>` (en-US) 元素
<font> - HTML:超文本標記語言
<font> ====== **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 概要 -- *HTML Font 元素*(`<font>`)定義了該內容的字體大小、顏色與表現。 **備註:** 不要使用這個元素!儘管它在 HTML 3.2 規範化,但在 HTML 4.01,因為該元件只有裝飾用途的理由而遭棄用,接著在 HTML5 廢棄。從 HTML 4 開始,HTML 不能在 `<style>` (en-US) 元素,或各元素 **style** 屬性以外,表現任何樣式資訊。今後的網頁開發,樣式化要用 CSS。`<font>` 元素的行為,能透過 CSS 屬性實現,也更好控制。 屬性 -- 如同其他 HTML 元素,這個元素支援全域屬性 (en-US)。 `color` 這個屬性可以藉由顏色名字或是十六進位的 #RRGGBB 格式,來配置文字的顏色。 `face` 這個屬性列出了一個或多個逗號分隔的字體名稱。 The document text in the default style is rendered in the first font face that the client's browser supports. 如果在用戶端的系統並沒有安裝這個字體,瀏覽器會在該系統使用預設的 proportional 或是 fixed-width 字體。 `size` 這個屬性藉由數字或相對值指定文字大小。數字是由最小的 `1` 到最大的 `7` 之間,且預設為 `3` 的數值表示。也可以用諸如 `+2` 或 `-3` 的相對值指定, which set it relative to the value of the `size` (en-US) attribute of the `<basefont>` (en-US) element, or relative to 3, the default value, if none does exist. DOM 介面 ------ 這個元素 implements `HTMLFontElement` (en-US) 介面。 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
<table>(表格元素) - HTML:超文本標記語言
<table>(表格元素) ============= **HTML `<table>` 元件**代表表格數據 ── 換句話說,就是透過二維資料表來呈現資訊。 嘗試一下 ---- | | | | --- | --- | | 內容類型 (en-US) | 流內容 (en-US) | | 允許內容 | 按照以下順序: 1. 一個可選的`<caption>` (en-US)元素, 2. 零個或更多的`<colgroup>` (en-US)元素, 3. 一個可選的`<thead>` (en-US)元素, 4. 一個在以下元素之前或之後的可選 `<tfoot>` (en-US) 元素: * 零個或更多的`<tbody>` (en-US)元素, * 或者,一個或更多的`<tr>` (en-US)元素 | | 標籤省略 | None, both the starting and ending tag are mandatory. | | 允許父元素 | Any element that accepts flow content | | 允許 ARIA 規則 | Any | | DOM 介面 | `HTMLTableElement` (en-US) | 屬性 -- 這個元件包含了 全域屬性(global attributes) (en-US)。 ### 棄用屬性 `align` 已棄用 這個枚舉屬性會指示表格中的文字要如何對齊。可用值如下:left:意思是表格應該顯示在文件的左方。 * center:意思是表格應該顯示在文件的中間。 * right:意思是表格應該顯示在文件的右方。在 CSS 要得出類似效果,應該設定 `margin-left` (en-US) 與 `margin-right` (en-US);如果要置中,則要把 `margin` (en-US) 屬性設定為 `0 auto`。 `bgcolor` 已棄用 定義表格的背景與內容顏色。它使用六位十六進制 RGB code (en-US),前缀需要加上 '`#`' 。也可以用預先定義的顏色字串 (en-US)可用。在 CSS 要得出類似效果,應該使用 `background-color` 屬性。 `border` 已棄用 這個屬性以像素為單位,定義了圍繞於表格框架的大小。如果設為 0,代表 `frame` 屬性為空。在 CSS 要得出類似效果,應該使用 `border` (en-US) 屬性。 `cellpadding` 已棄用 這個屬性定義了元件與邊界線之間的空白,以及要不要顯示。如果輸入像素,像素長度的空白會套用到四個邊;如果輸入百分比,內容將居中、整體的垂直空間(上與下)會使用這個百分比表示。橫向空間(左與右)也適用這個規則。在 CSS 要得出類似效果,應該對 `<table>` 屬性使用 `border-collapse` (en-US);並對 `<td>` (en-US) 使用 `padding` (en-US)。 `cellspacing` 已棄用 This attribute defines the size of the space between two cells in a percentage value or pixels. The attribute is applied both horizontally and vertically, to the space between the top of the table and the cells of the first row, the left of the table and the first column, the right of the table and the last column and the bottom of the table and the last row.To achieve a similar effect, apply the `border-spacing` (en-US) property to the `<table>` element. `border-spacing` does not have any effect if `border-collapse` (en-US) is set to collapse. `frame` 已棄用 這個枚舉屬性定義圍繞在表格邊框的哪一邊要顯示。在 CSS 要得出類似效果,應該使用 `border-style` (en-US) 與 `border-width` (en-US) 屬性。 `rules` 已棄用 這個枚舉屬性定義諸如線條之類的規則,要如何出現在表格。它擁有以下數值:`none`,代表沒有任何規則上的指示。這是預設值。 * `groups`,只標示行群組和列群組(行群組由 `<thead>` (en-US)、`<tbody>` (en-US)、和 `<tfoot>` (en-US) 定義;列群組由 `<col>` (en-US) 與 `<colgroup>` (en-US) 定義); * `rows`,會創立一組標示行的規則; * `columns`,會創立一組標示列的規則; * `all`,會創立一組同時標示行與列的規則。在 CSS 要得出類似效果,應該針對 `<thead>` (en-US)、`<tbody>` (en-US)、`<tfoot>` (en-US)、`<col>` (en-US)、`<colgroup>` (en-US) 元素使用 `border` (en-US) 屬性。 `summary` 已棄用 這個屬性定義了總結表格的替代文字。請改用 `<caption>` (en-US) 元素。 `width` 已棄用 這個屬性定義了表格的寬度。請改用 CSS `width` 屬性。 範例 -- ### 簡單的表格 ```html <table> <tr> <td>John</td> <td>Doe</td> </tr> <tr> <td>Jane</td> <td>Doe</td> </tr> </table> ``` ### 更多範例 ```html <p>Simple table with header</p> <table> <tr> <th>First name</th> <th>Last name</th> </tr> <tr> <td>John</td> <td>Doe</td> </tr> <tr> <td>Jane</td> <td>Doe</td> </tr> </table> <p>Table with thead, tfoot, and tbody</p> <table> <thead> <tr> <th>Header content 1</th> <th>Header content 2</th> </tr> </thead> <tfoot> <tr> <td>Footer content 1</td> <td>Footer content 2</td> </tr> </tfoot> <tbody> <tr> <td>Body content 1</td> <td>Body content 2</td> </tr> </tbody> </table> <p>Table with colgroup</p> <table> <colgroup span="4"></colgroup> <tr> <th>Countries</th> <th>Capitals</th> <th>Population</th> <th>Language</th> </tr> <tr> <td>USA</td> <td>Washington D.C.</td> <td>309 million</td> <td>English</td> </tr> <tr> <td>Sweden</td> <td>Stockholm</td> <td>9 million</td> <td>Swedish</td> </tr> </table> <p>Table with colgroup and col</p> <table> <colgroup> <col style="background-color: #0f0" /> <col span="2" /> </colgroup> <tr> <th>Lime</th> <th>Lemon</th> <th>Orange</th> </tr> <tr> <td>Green</td> <td>Yellow</td> <td>Orange</td> </tr> </table> <p>Simple table with caption</p> <table> <caption> Awesome caption </caption> <tr> <td>Awesome data</td> </tr> </table> ``` ``` table { border-collapse: collapse; border-spacing: 0px; } table, th, td { padding: 5px; border: 1px solid black; } ``` 無障礙議題 ----- ### Caption 提供 `<caption>` (en-US) 元素,以便清晰而簡潔地描述表格主旨。他能讓用戶決定自己是否該閱讀表格內容,還是要略過就好。 如此也能幫助螢幕閱讀器之類的輔具使用者、視力條件差、還有認知障礙的人。 * MDN Adding a caption to your table with <caption> (en-US) * Caption & Summary • Tables • W3C WAI Web Accessibility Tutorials ### Scope 行列 雖然在 HTML5 裡面 `scope` (en-US) 屬性已經過時,但很多螢幕閱讀器會利用這屬性,複製不使用屏幕閱讀器的人的視覺關聯,以便推斷可能的視覺位置。 #### 示例 ```html <table> <caption> Color names and values </caption> <tbody> <tr> <th scope="col">Name</th> <th scope="col">HEX</th> <th scope="col">HSLa</th> <th scope="col">RGBa</th> </tr> <tr> <th scope="row">Teal</th> <td><code>#51F6F6</code></td> <td><code>hsla(180, 90%, 64%, 1)</code></td> <td><code>rgba(81, 246, 246, 1)</code></td> </tr> <tr> <th scope="row">Goldenrod</th> <td><code>#F6BC57</code></td> <td><code>hsla(38, 90%, 65%, 1)</code></td> <td><code>rgba(246, 188, 87, 1)</code></td> </tr> </tbody> </table> ``` 在 `<th>` (en-US) 元素提供 `scope="col"` 的宣告,有助於描述該單位屬於第一列。在 `<td>` (en-US) 元素提供 `scope="row"` 則有助於描述該單位屬於第一行。 * MDN Tables for visually impaired users (en-US) * Tables with two headers • Tables • W3C WAI Web Accessibility Tutorials * Tables with irregular headers • Tables • W3C WAI Web Accessibility Tutorials * H63: Using the scope attribute to associate header cells and data cells in data tables | W3C Techniques for WCAG 2.0 ### 複雜的表格 針對單格複雜到無法歸類於直向或橫向的表格,諸如螢幕閱讀器之類的輔助技術,可能就無法解析。在這種情況下,通常就需要 `colspan` (en-US) 與 `rowspan` (en-US) 屬性。 理想情況下,可以考慮使用其他方式來呈現表格的內容,例如把表格切分到不必依賴 `colspan` 和 `rowspan` 屬性。除了幫助使用輔助技術的人了解表格的內容之外,這樣也會使認知障礙者受益,因為他們可能難以理解表格佈局描述的關聯。 `如果表格無法切分,請結合 [`id`](/zh-TW/docs/Web/HTML/Global_attributes#id) 與 [`headers`](/zh-TW/docs/Web/HTML/Element/td#headers) 使用,以便程序化地關聯各表格單位與標題。` * `MDN Tables for visually impaired users` (en-US) * `Tables with multi-level headers • Tables • W3C WAI Web Accessibility Tutorials` * `H43: Using id and headers attributes to associate data cells with header cells in data tables | Techniques for W3C WCAG 2.0` 規範 -- | Specification | | --- | | HTML Standard # the-table-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * CSS properties that may be especially useful to style the `<table>` element: + `width` to control the width of the table; + `border` (en-US), `border-style` (en-US), `border-color`, `border-width` (en-US), `border-collapse` (en-US), `border-spacing` (en-US) to control the aspect of cell borders, rules and frame; + `margin` (en-US) and `padding` (en-US) to style the individual cell content; + `text-align` (en-US) and `vertical-align` (en-US) to define the alignment of text and cell content.
<frameset> - HTML:超文本標記語言
<frameset> ========== **已棄用:** 不推薦使用此功能。雖可能有一些瀏覽器仍然支援它,但也許已自相關的網頁標準中移除、正準備移除、或僅為了維持相容性而保留。避免使用此功能,盡可能更新現有程式;請參考頁面底部的相容性表格來下決定。請注意:本功能可能隨時停止運作。 概要 -- `<frameset>` 是用以包含 `<frame>` (en-US) 元素的元素。 **備註:** 因為使用框架的推薦是 `<iframe>` (en-US),這個元素一般不會在現在的網站出現。 屬性 -- 如同其他 HTML 元素,這個元素支持全域屬性。 `cols` 這個屬性指定了橫向框架的數量和尺寸。 `rows` 這個屬性指定了直向框架的數量和尺寸。 範例 -- ```html <frameset cols="50%,50%"> <frame src="https://developer.mozilla.org/en/HTML/Element/frameset" /> <frame src="https://developer.mozilla.org/en/HTML/Element/frame" /> </frameset> ``` 參見 -- * `<frame>` (en-US) * `<iframe>` (en-US)
<hr> - HTML:超文本標記語言
<hr> ==== **HTML** 的\*\* `<hr>` 元素\*\*代表在段落層級的焦點轉換(如故事中的場景轉換或某個小節裡的主題移轉)。在之前的 HTML 版本,它代表著一條水平標線。在視覺瀏覽器裡,它現在可能還是以水平標線的型式呈現;但它已經被重新定義為一個語義上的用詞,而不是呈現上的。 | 內容類型 (en-US) | 流內容 (en-US). | | --- | --- | | Permitted content | 否。這是個 empty element. | | 標籤省略 | 一定要有起始標籤、同時絕不能有結束標籤 | | Permitted parent elements | 任何允許流內容 (en-US)的元素。 | | DOM interface | `HTMLHRElement` (en-US) | 屬性 -- 這個元素支持全域屬性 (en-US)。 `align` 已棄用 設罝頁面上標線的對齊方式。如果沒有指定,預設值是:`left。` `color` 非標準 用色彩名或 16 進位值設罝標線的顏色。 `noshade` 已棄用 設置這個標線沒有陰影。 `size` 已棄用 設置標線的高度,單位是 px。. `width` 已棄用 設置標線的長度,單位是 px;或者也可以用頁面寛度的百分比 (%)表示。 範例 -- ```html <p> This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. </p> <hr /> <p> This is second paragraph of text. This is second paragraph of text. This is second paragraph of text. This is second paragraph of text. </p> ``` 上面的 HTML 會輸出: This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. --- This is second paragraph of text. This is second paragraph of text. This is second paragraph of text. This is second paragraph of text. 規範 -- | Specification | | --- | | HTML Standard # the-hr-element | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參照 (see also) ------------- * `<p>` (en-US)