HTMLCanvasElement:toDataURL() 方法
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
HTMLCanvasElement.toDataURL() 方法會回傳一個包含圖片展示的資料 URL,其格式由 type 參數指定。
可以指定想要的檔案格式與圖片品質。若未指定檔案格式,或不支援給定的格式,則資料會匯出為 image/png。換句話說,如果對任何其他請求的 type 回傳值是以 data:image/png 開頭,則表示不支援該格式。
瀏覽器必須支援 image/png;許多瀏覽器也支援其他格式,包含 image/jpeg 與 image/webp。
對於支援編碼解析度後設資料的檔案格式,建立的圖片資料解析度將為 96dpi。
警告:toDataURL() 會將整張圖片編碼為記憶體內的字串。對於較大的圖片,這可能會影響效能,且在指派給 HTMLImageElement.src 時,甚至可能超出瀏覽器的 URL 長度限制。你通常應該優先使用 toBlob() 搭配 URL.createObjectURL() 來代替。
語法
toDataURL()
toDataURL(type)
toDataURL(type, quality)
參數
type選擇性-
指示圖片格式的字串。預設類型為
image/png;若不支援指定的類型,也會使用此圖片格式。 quality選擇性-
一個
0到1之間的Number,指示在使用支援失真壓縮的檔案格式(如image/jpeg或image/webp)建立圖片時所使用的圖片品質。若未指定此選項,或數值超出允許範圍,使用者代理將使用其預設的品質數值。
回傳值
包含請求 data URL 的字串。
若畫布的高度或寬度為 0 或大於最大畫布尺寸,則回傳字串 "data:,"。
例外
SecurityError-
畫布的點陣圖不是來源乾淨的;其內容至少有一部分是(或可能是)從文件本身載入來源以外的網站載入的。
範例
給定這個 <canvas> 元素:
<canvas id="canvas" width="5" height="5"></canvas>
你可以用下列程式碼取得畫布的資料 URL:
const canvas = document.getElementById("canvas");
const dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
設定 jpeg 的圖片品質
const fullQuality = canvas.toDataURL("image/jpeg", 1.0);
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ…9oADAMBAAIRAxEAPwD/AD/6AP/Z"
const mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
const lowQuality = canvas.toDataURL("image/jpeg", 0.1);
範例:動態變更圖片
你可以搭配滑鼠事件使用此技術,以動態變更圖片(此範例為灰階與彩色的切換):
HTML
<img class="grayscale" src="myPicture.png" alt="我的圖片描述" />
JavaScript
function showColorImg() {
this.style.display = "none";
this.nextSibling.style.display = "inline";
}
function showGrayImg() {
this.previousSibling.style.display = "inline";
this.style.display = "none";
}
function removeColors() {
const images = document.getElementsByClassName("grayscale");
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
for (const colorImg of images) {
const width = colorImg.offsetWidth;
const height = colorImg.offsetHeight;
canvas.width = width;
canvas.height = height;
ctx.drawImage(colorImg, 0, 0);
const imgData = ctx.getImageData(0, 0, width, height);
const pix = imgData.data;
const pixLen = pix.length;
for (let pixel = 0; pixel < pixLen; pixel += 4) {
pix[pixel + 2] =
pix[pixel + 1] =
pix[pixel] =
(pix[pixel] + pix[pixel + 1] + pix[pixel + 2]) / 3;
}
ctx.putImageData(imgData, 0, 0);
const grayImg = new Image();
grayImg.src = canvas.toDataURL();
grayImg.onmouseover = showColorImg;
colorImg.onmouseout = showGrayImg;
ctx.clearRect(0, 0, width, height);
colorImg.style.display = "none";
colorImg.parentNode.insertBefore(grayImg, colorImg);
}
}
removeColors();
規範
| Specification |
|---|
| HTML> # dom-canvas-todataurl-dev> |