Javascript canvas to blob

JavaScript Canvas to Blob

Canvas to Blob is a polyfill for Browsers that don’t support the standard JavaScript HTMLCanvasElement.toBlob method.

It can be used to create Blob objects from an HTML canvas element.

Setup

npm install blueimp-canvas-to-blob 

This will install the JavaScript files inside ./node_modules/blueimp-canvas-to-blob/js/ relative to your current directory, from where you can copy them into a folder that is served by your web server.

Next include the minified JavaScript Canvas to Blob script in your HTML markup:

Or alternatively, include the non-minified version:

Usage

You can use the canvas.toBlob() method in the same way as the native implementation:

var canvas = document.createElement('canvas') // Edit the canvas . if (canvas.toBlob)  canvas.toBlob(function (blob)  // Do something with the blob object, // e.g. create multipart form data for file uploads: var formData = new FormData() formData.append('file', blob, 'image.jpg') // . >, 'image/jpeg') > 

Requirements

The JavaScript Canvas to Blob function has zero dependencies.

However, it is a very suitable complement to the JavaScript Load Image function.

Browsers

The following browsers have native support for HTMLCanvasElement.toBlob:

  • Chrome 50+
  • Firefox 19+
  • Safari 11+
  • Mobile Chrome 50+ (Android)
  • Mobile Firefox 4+ (Android)
  • Mobile Safari 11+ (iOS)
  • Edge 79+

Browsers which implement the following APIs support canvas.toBlob() via polyfill:

This includes the following browsers:

  • Chrome 20+
  • Firefox 13+
  • Safari 8+
  • Mobile Chrome 25+ (Android)
  • Mobile Firefox 14+ (Android)
  • Mobile Safari 8+ (iOS)
  • Edge 74+
  • Edge Legacy 12+
  • Internet Explorer 10+

API

In addition to the canvas.toBlob() polyfill, the JavaScript Canvas to Blob script exposes its helper function dataURLtoBlob(url) :

// Uncomment the following line when using a module loader like webpack: // var dataURLtoBlob = require('blueimp-canvas-to-blob') // black+white 3x2 GIF, base64 data: var b64 = 'R0lGODdhAwACAPEAAAAAAP///yZFySZFySH5BAEAAAIALAAAAAADAAIAAAIDRAJZADs=' var url = 'data:image/gif;base64,' + b64 var blob = dataURLtoBlob(url) 

Test

License

The JavaScript Canvas to Blob script is released under the MIT license.

Источник

HTMLCanvasElement.toBlob()

Метод 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-функция с результирующим объектом Blob в качестве единственного аргумента.

Аргумент типа DOMString определяющий формат изображения. По умолчанию image/png .

Аргумент типа Number со значением от 0 до 1 , определяющий качество изображения, если заявлен MIME-тип image/jpeg или image/webp . Если этот аргумент содержит нечто иное, для определения качества изображения будет использовано значение по умолчанию. Остальные аргументы проигнорируются.

Возвращаемое значение

Примеры

Получение файла, представленного в canvas

Как только вы нарисовали содержимое в canvas , вы можете сконвертировать его в файл изображения любого поддерживаемого формата. Ниже приведён фрагмент кода, для примера, принимает изображение в элементе с и получает его копию в виде PNG изображения, затем добавляет в документ новый элемент , исходное изображение которого создано с помощью холста.

var canvas = document.getElementById('canvas'); canvas.toBlob(function(blob)  var newImg = document.createElement('img'), url = URL.createObjectURL(blob); newImg.onload = function()  // больше не нужно читать blob, поэтому он отменён URL.revokeObjectURL(url); >; newImg.src = url; document.body.appendChild(newImg); >); 

Обратите внимание, что здесь мы создаём изображение PNG; если вы добавите второй параметр в вызов toBlob() , вы сможете определить тип необходимого изображения. Например, чтобы получить изображение в формате JPEG:

.toBlob(function(blob). >, 'image/jpeg', 0.95); // JPEG в 95% качестве 

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

Это использует -moz-parse для преобразования cnavas в 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'); 

Сохранение toBlob на диске ОС(chrome/add-on context only)

Примечание: Этот метод сохраняет его на рабочем столе и полезен только в контексте Firefox chrome или дополнительном коде, поскольку API ОС не присутствуют на веб-сайтах.

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

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Полифил

Полифил, основанный на toDataURL, со слабой производительностью.

if (!HTMLCanvasElement.prototype.toBlob) < Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', < value: function (callback, type, quality) < var dataURL = this.toDataURL(type, quality).split(',')[1]; setTimeout(function() < var binStr = atob( dataURL ), len = binStr.length, arr = new Uint8Array(len); for (var i = 0; i < len; i++ ) < arr[i] = binStr.charCodeAt(i); >callback( new Blob( [arr], ) ); >); > >); >

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JavaScript Canvas to Blob is a function to convert canvas elements into Blob objects.

License

blueimp/JavaScript-Canvas-to-Blob

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JavaScript Canvas to Blob

Canvas to Blob is a polyfill for Browsers that don’t support the standard JavaScript HTMLCanvasElement.toBlob method.

It can be used to create Blob objects from an HTML canvas element.

npm install blueimp-canvas-to-blob

This will install the JavaScript files inside ./node_modules/blueimp-canvas-to-blob/js/ relative to your current directory, from where you can copy them into a folder that is served by your web server.

Next include the minified JavaScript Canvas to Blob script in your HTML markup:

script src pl-s">js/canvas-to-blob.min.js">script>

Or alternatively, include the non-minified version:

script src pl-s">js/canvas-to-blob.js">script>

You can use the canvas.toBlob() method in the same way as the native implementation:

var canvas = document.createElement('canvas') // Edit the canvas . if (canvas.toBlob)  canvas.toBlob(function (blob)  // Do something with the blob object, // e.g. create multipart form data for file uploads: var formData = new FormData() formData.append('file', blob, 'image.jpg') // . >, 'image/jpeg') >

The JavaScript Canvas to Blob function has zero dependencies.

However, it is a very suitable complement to the JavaScript Load Image function.

The following browsers have native support for HTMLCanvasElement.toBlob:

  • Chrome 50+
  • Firefox 19+
  • Safari 11+
  • Mobile Chrome 50+ (Android)
  • Mobile Firefox 4+ (Android)
  • Mobile Safari 11+ (iOS)
  • Edge 79+

Browsers which implement the following APIs support canvas.toBlob() via polyfill:

This includes the following browsers:

  • Chrome 20+
  • Firefox 13+
  • Safari 8+
  • Mobile Chrome 25+ (Android)
  • Mobile Firefox 14+ (Android)
  • Mobile Safari 8+ (iOS)
  • Edge 74+
  • Edge Legacy 12+
  • Internet Explorer 10+

In addition to the canvas.toBlob() polyfill, the JavaScript Canvas to Blob script exposes its helper function dataURLtoBlob(url) :

// Uncomment the following line when using a module loader like webpack: // var dataURLtoBlob = require('blueimp-canvas-to-blob') // black+white 3x2 GIF, base64 data: var b64 = 'R0lGODdhAwACAPEAAAAAAP///yZFySZFySH5BAEAAAIALAAAAAADAAIAAAIDRAJZADs=' var url = 'data:image/gif;base64,' + b64 var blob = dataURLtoBlob(url)

The JavaScript Canvas to Blob script is released under the MIT license.

About

JavaScript Canvas to Blob is a function to convert canvas elements into Blob objects.

Источник

Читайте также:  Java lang stackoverflowerror exception while updating neighbours
Оцените статью