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

浏览器兼容性

另见