HTMLCanvasElement: toBlob() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

HTMLCanvasElement.toBlob() 方法创建一个表示画布中图像的 Blob 对象。此文件可能由用户代理决定缓存在磁盘上或存储在内存中。

可以指定所需的文件格式和图像质量。如果未指定文件格式,或者给定的格式不受支持,则数据将导出为 image/png。浏览器必须支持 image/png;许多浏览器还将支持其他格式,包括 image/jpegimage/webp

对于支持编码分辨率元数据的文件格式,创建的图像分辨率为 96dpi。

语法

js
toBlob(callback)
toBlob(callback, type)
toBlob(callback, type, quality)

参数

回调

一个回调函数,以包含 Blob 对象的单个参数。如果由于任何原因无法创建图像,则可以传递 null

type 可选

一个字符串,指示图像格式。默认类型为 image/png;如果给定的类型不受支持,也将使用该类型。

quality 可选

一个介于 01 之间的 Number,指示在使用支持有损压缩的文件格式(如 image/jpegimage/webp)创建图像时要使用的图像质量。如果未指定此选项,或者该数字超出了允许的范围,则用户代理将使用其默认质量值。

返回值

无(undefined)。

异常

SecurityError

画布的位图不是原始的;至少部分内容已从与文档加载源相同的站点加载,或者可能已从其他站点加载。

示例

获取表示画布的文件

将内容绘制到画布后,您可以将其转换为任何支持的图像格式的文件。例如,下面的代码片段获取 ID 为“canvas”的 <canvas> 元素中的图像,将其作为 PNG 图像获取副本,然后将一个新的 <img> 元素附加到文档中,其源图像就是使用画布创建的。

js
const canvas = document.getElementById("canvas");

canvas.toBlob((blob) => {
  const newImg = document.createElement("img");
  const url = URL.createObjectURL(blob);

  newImg.src = url;
  document.body.appendChild(newImg);
});

请注意,此处我们创建的是 PNG 图像;如果您向 toBlob() 调用添加第二个参数,您可以指定用户代理支持的另一种图像类型。例如,要以 JPEG 格式获取图像

js
canvas.toBlob(
  (blob) => {
    /* … */
  },
  "image/jpeg",
  0.95,
); // JPEG at 95% quality

请注意,我们不会在图像加载后立即撤销对象 URL,因为这样做会使图像无法用于用户交互(例如右键单击保存图像或在新标签页中打开它)。对于长期运行的应用程序,您应该在不再需要对象 URL 时撤销它们(例如,当图像从 DOM 中移除时),通过调用 URL.revokeObjectURL() 方法并将对象 URL 字符串作为参数传递来释放内存。

将 Canvas 转换为 ico (仅限 Mozilla)

这使用 -moz-parse 将 Canvas 转换为 ico,因此仅在 Firefox 中有效。Windows XP 不支持从 PNG 转换为 ico,因此它改用 bmp。通过设置 download 属性来创建下载链接。download 属性的值是它将用作文件名。

js
const canvas = document.getElementById("canvas");
const d = canvas.width;
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(d / 2, 0);
ctx.lineTo(d, d);
ctx.lineTo(0, d);
ctx.closePath();
ctx.fillStyle = "yellow";
ctx.fill();

function blobCallback(iconName) {
  return (b) => {
    const a = document.createElement("a");
    a.textContent = "Download";
    document.body.appendChild(a);
    a.style.display = "block";
    a.download = `${iconName}.ico`;
    a.href = window.URL.createObjectURL(b);
  };
}
canvas.toBlob(
  blobCallback("passThisString"),
  "image/vnd.microsoft.icon",
  "-moz-parse-options:format=bmp;bpp=32",
);

使用 OS.File 将 toBlob 保存到磁盘 (仅 Chrome/附加组件上下文)

注意:此技术将其保存到桌面,并且仅在 Firefox chrome 上下文或附加组件代码中有用,因为网站上不存在 OS API。

js
const canvas = document.getElementById("canvas");
const d = canvas.width;
ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(d / 2, 0);
ctx.lineTo(d, d);
ctx.lineTo(0, d);
ctx.closePath();
ctx.fillStyle = "yellow";
ctx.fill();

function blobCallback(iconName) {
  return (b) => {
    const r = new FileReader();
    r.onloadend = () => {
      // r.result contains the ArrayBuffer.
      Cu.import("resource://gre/modules/osfile.jsm");
      const writePath = OS.Path.join(
        OS.Constants.Path.desktopDir,
        `${iconName}.ico`,
      );
      const promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), {
        tmpPath: `${writePath}.tmp`,
      });
      promise.then(
        () => {
          console.log("successfully wrote file");
        },
        () => {
          console.log("failure writing file");
        },
      );
    };
    r.readAsArrayBuffer(b);
  };
}

canvas.toBlob(
  blobCallback("passThisString"),
  "image/vnd.microsoft.icon",
  "-moz-parse-options:format=bmp;bpp=32",
);

规范

规范
HTML
# dom-canvas-toblob-dev

浏览器兼容性

另见