HTMLCanvasElement.toBlob()

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

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

语法

canvas.toBlob(callback, type, encoderOptions);

参数

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

返回值

无。

异常

SecurityError
canvas“被污染”的情况下不能使用此方法

示例

将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
HTML Living Standard
HTMLCanvasElement.toBlob
Living Standard No change since the latest snapshot, HTML5
HTML 5.1
HTMLCanvasElement.toBlob
Recommendation No change
HTML5
HTMLCanvasElement.toBlob
Recommendation Snapshot of the HTML Living Standard containing the initial definition.

浏览器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
toBlobChrome Full support 50Edge No support NoFirefox Full support 19IE Full support 10
Prefixed
Full support 10
Prefixed
Prefixed Implemented with the vendor prefix: ms
Opera Full support 37Safari Full support 11WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 4Opera Android Full support 37Safari iOS Full support 11Samsung Internet Android Full support 5.0
Image quality parameterChrome Full support 50Edge No support NoFirefox Full support 25IE No support NoOpera Full support YesSafari No support NoWebView Android Full support 50Chrome Android No support NoFirefox Android Full support 25Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Requires a vendor prefix or different name for use.
Requires a vendor prefix or different name for use.

扩展阅读