HTMLCanvasElement: toDataURL() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLCanvasElement.toDataURL() 方法返回一個 data URL,其中包含以 type 引數指定的格式表示的影像。

可以指定所需的影像格式和影像質量。如果未指定影像格式,或者指定的格式不受支援,則資料將匯出為 image/png。換句話說,如果返回的值以 data:image/png 開頭,那麼對於任何其他請求的 type,該格式均不受支援。

瀏覽器必須支援 image/png;許多瀏覽器將支援其他格式,包括 image/jpegimage/webp

建立的影像資料對於支援編碼解析度元資料的影像格式的解析度為 96dpi。

警告: toDataURL() 將整個影像編碼為記憶體字串。對於較大的影像,這可能會影響效能,甚至在分配給 HTMLImageElement.src 時可能超出瀏覽器的 URL 長度限制。通常,您應該首選 toBlob(),並結合使用 URL.createObjectURL()

語法

js
toDataURL()
toDataURL(type)
toDataURL(type, quality)

引數

type 可選

一個指示影像格式的字串。預設型別為 image/png;如果指定的型別不受支援,也將使用此影像格式。

quality 可選

一個介於 01 之間的 Number,指示在使用支援有失真壓縮的檔案格式(如 image/jpegimage/webp)建立影像時要使用的影像質量。如果未指定此選項,或者該數字超出了允許的範圍,則使用者代理將使用其預設質量值。

返回值

包含請求的 data URL 的字串。

如果畫布的高度或寬度為 0 或大於 最大畫布尺寸,則返回字串 "data:,"

異常

SecurityError

畫布的點陣圖不是源乾淨的;其部分內容已載入或可能已從與載入文件本身不同的網站載入。

示例

給定此 <canvas> 元素

html
<canvas id="canvas" width="5" height="5"></canvas>

您可以使用以下幾行程式碼獲取畫布的 data-URL

js
const canvas = document.getElementById("canvas");
const dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"

設定 JPEG 的影像質量

js
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

html
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />

JavaScript

js
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();

規範

規範
HTML
# dom-canvas-todataurl-dev

瀏覽器相容性

另見