Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.
Метод HTMLCanvasElement.toBlob()
создаёт объект Blob
представляющий изображение, содержащееся в canvas
; этот файл может быть закеширован на диске или храниться в памяти на усмотрение пользователя (at the discretion of the user agent). Если параметр mimeType
не определён, типом изображения считается image/png
. Созданное изображение имеет разрешение 96dpi.
Третий аргумент используется для изображений с MIME-типом image/jpeg
для определения его качества.
Синтаксис
void canvas.toBlob(callback, mimeType, qualityArgument);
Параметры
- callback
- Callback-функция с результирующим объектом
Blob
в качестве единственного аргумента. mimeType
Необязательный- Аргумент типа
DOMString
определяющий формат изображения. По умолчаниюimage/png
. qualityArgument
Необязательный- Аргумент типа
Number
со значением от0
до1
, определяющий качество изображения, если заявлен MIME-типimage/jpeg
илиimage/webp
. Если этот аргумент содержит нечто иное, для определения качества изображения будет использовано значение по умолчанию. Остальные аргументы проигнорируются.
Возвращаемое значение
Не возвращает ничего.
Примеры
Получение файла, представленного в canvas
Как только вы нарисовали содержимое в canvas
, вы можете сконвертировать его в файл изображения любого поддерживаемого формата. Ниже приведён фрагмент кода, для примера, принимает изображение в элементе <canvas>
с ID = "canvas" и получает его копию в виде PNG изображения, затем добавляет в документ новый элемент <img>
, исходное изображение которого создано с помощью холста.
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
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');
Спецификации
Specification | Status | Comment |
---|---|---|
HTML Living Standard Определение 'HTMLCanvasElement.toBlob' в этой спецификации. |
Живой стандарт | No change since the latest snapshot, HTML5 |
HTML 5.1 Определение 'HTMLCanvasElement.toBlob' в этой спецификации. |
Рекомендация | No change |
HTML5 Определение 'HTMLCanvasElement.toBlob' в этой спецификации. |
Рекомендация | Snapshot of the HTML Living Standard containing the initial definition. |
Поддержка браузерами
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 50 | 19 (19) | 10ms | (Да) | (Да)[1] |
Image quality parameter | 50 | 25 (25) | Нет | (Да) | Нет |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | Нет | 50 | 19.0 (19) | ? | Нет | ? | 50 |
Image quality parameter | Нет | 50 | 25.0 (25) | ? | Нет | ? | 50 |
[1] See Баг WebKit 71270.
Полифилл
Полифилл, основанный на toDataURL, со слабой производительностью.
if (!HTMLCanvasElement.prototype.toBlob) { Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', { value: function (callback, type, quality) { var canvas = this; setTimeout(function() { var binStr = atob( canvas.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'} ) ); }); } }); }
Смотрите также
- The interface defining it,
HTMLCanvasElement
. Blob