HTMLCanvasElement.toBlob()

HTMLCanvasElement.toBlob() 方法创造Blob对象,用以展示canvas上的图片;这个图片文件可以被缓存或保存到本地,由用户代理端自行决定。如不特别指明,图片的类型默认为 image/png,分辨率为96dpi。

第三个参数用于针对image/jpeg格式的图片进行输出图片的质量设置。

语法

void canvas.toBlob(callback, type, encoderOptions);

参数

callback
回调函数,可获得一个单独的Blob对象参数。
type 可选
DOMString类型,指定图片格式,默认格式为image/png
encoderOptions 可选
Number类型,值在0与1之间,当请求图片格式为image/jpeg或者image/webp时用来指定图片展示质量。如果这个参数的值不在指定类型与范围之内,则使用默认值,其余参数将被忽略。

返回值

无。

示例

将canvas图像转换为文件

当一个内容画到canvas上时,我们可以将它生成任何一个格式支持的图片文件。比如,下面的代码段获得了id为“canvas”的<canvas>元素中的图像,复制成一个PNG图,在文档中加入一个新的<img>元素,这个<img>元素的源图就是使用canvas创建的那个图像。 

var canvas = document.getElementById("canvas");

canvas.toBlob(function(blob) {
  var newImg = document.createElement("img"),
      url = URL.createObjectURL(blob);

  newImg.onload = function() {
    // no longer need to read the blob so it's revoked
    URL.revokeObjectURL(url);
  };

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

注意,我们这里创建的是PNG图片;如果在toBlob()传入第二个参数,就可以指定图片格式。例如,生成JPEG格式的图片:

 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality

将canvas转换为ico(仅限Mozilla)

使用-moz-parse来将canvas转换为ico。Windows XP不支持将PNG转为ico,因此转为bmp作为代替。设置下载属性,生成下载链接。下载属性的值将被用来作为文件名。

var canvas = document.getElementById("canvas");
var 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 function(b) {
    var 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');

Save toBlob to disk with OS.File (chrome/add-on context only)

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

var canvas = document.getElementById("canvas");
var 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 function(b) {
    var r = new FileReader();
    r.onloadend = function () {
    // r.result contains the ArrayBuffer.
    Cu.import('resource://gre/modules/osfile.jsm');
    var writePath = OS.Path.join(OS.Constants.Path.desktopDir, 
                                 iconName + '.ico');
    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), 
                                      {tmpPath:writePath + '.tmp'});
    promise.then(
      function() {
        console.log('successfully wrote file');
      },
      function() {
        console.log('failure writing file')
      }
    );
  };
  r.readAsArrayBuffer(b);
  }
}

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

Polyfill

A low performance polyfill based on toDataURL.

if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}

文档

Specification Status Comment
WHATWG HTML Living Standard
HTMLCanvasElement.toBlob
Living Standard No change since the latest snapshot, HTML5
HTML5.1
HTMLCanvasElement.toBlob
Working Draft No change
HTML5
HTMLCanvasElement.toBlob
Recommendation Snapshot of the WHATWG HTML Living Standard containing the initial definition.

浏览器兼容

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 未实现[1] 19 (19) 10ms 未实现 未实现[2]
Image quality parameter (jpeg) 未实现 25 (25) 未实现 未实现 未实现
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 未实现 19.0 (19) ? 未实现 ?
Image quality parameter (jpeg) 未实现 未实现 25.0 (25) ? 未实现 ?

[1] Chrome does not implement this feature yet. See bug 67587.

[2] WebKit does not implement this feature yet. See WebKit bug 71270.

扩展阅读

文档标签和贡献者

 此页面的贡献者: ziyunfei, lyxuncle
 最后编辑者: ziyunfei,