Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

HTMLCanvasElement.toBlob()

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

EL metodo HTMLCanvasElement.toBlob() crea un objeto Blob que representa la imagen contenida en el canvas; este archivo puede ser cacheado en el disco oo guardado en la memoria a desicion del  user agent. Si la propiedad type no se especifica el tipo de la imagen será image/png. La imagen creada tiene una resolución de 96dpi.
El tercer argumento es usado con las imagenes  image/jpeg para especificar la calidad de salida.

Syntax

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

Parameters

callback
A callback function with the resulting Blob object as a single argument.
type Optional
A DOMString indicating the image format. The default type is image/png.
encoderOptions Optional
A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.

Return value

None.

Examples

Getting a file representing the canvas

Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the <canvas> element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the 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);
});

Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the image in JPEG format:

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

A way to convert a canvas to an ico (Mozilla only)

This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name.

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'} ) );
  }
 });
}

Specifications

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

Browser compatibility

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

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

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

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: kodamirmo
 Última actualización por: kodamirmo,