Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Provide a polyfill for canvas.toBlob instead of a custom global funct…

…ion.

Expose dataURLtoBlob as utility function.
  • Loading branch information...
commit 4e45358ce4e94be428eb043bfc272ff95060f197 1 parent 7b7994e
@blueimp authored
View
41 README.md
@@ -7,27 +7,23 @@ Include the (minified) JavaScript Canvas to Blob script in your HTML markup:
<script src="canvas-to-blob.min.js"></script>
```
-In your application code, use the **canvasToBlob()** function like this:
+The JavaScript Canvas to Blob script is a polyfill for the standard HTML [canvas.toBlob](http://www.w3.org/TR/html5/the-canvas-element.html#dom-canvas-toblob) method:
```js
var canvas = document.createElement('canvas');
/* ... your canvas manipulations ... */
-if(!canvasToBlob(
- canvas,
- function (blob) {
- // Do something with the blob object,
- // e.g. creating a multipart form for file uploads:
- var formData = new FormData();
- formData.append('file', blob, fileName);
- /* ... */
- },
- {
- type: fileType,
- name: fileName // Only used by Mozilla Firefox
- }
-)) {
- /* ... alternative code for unsupported browsers ... */
-};
+if (canvas.toBlob) {
+ canvas.toBlob(
+ function (blob) {
+ // Do something with the blob object,
+ // e.g. creating a multipart form for file uploads:
+ var formData = new FormData();
+ formData.append('file', blob, fileName);
+ /* ... */
+ },
+ 'image/jpeg'
+ );
+}
```
## Requirements
@@ -36,9 +32,16 @@ The JavaScript Canvas to Blob function has zero dependencies.
However, Canvas to Blob is a very suitable complement to the [JavaScript Load Image](https://github.com/blueimp/JavaScript-Load-Image) function.
## API
-The **canvasToBlob()** function expects a [canvas](https://developer.mozilla.org/en/HTML/Element/canvas) element as first argument and a callback function as second argument. An options object with the properties name (e.g. "image.png") and image (e.g. "image/png") can be provided as optional third argument.
+In addition to the **canvas.toBlob** polyfill, the JavaScript Canvas to Blob script provides one additional function called **dataURLtoBlob**, which is added to the global window object if no AMD loader is used to load the script:
-The function returns **true** if the browser supports canvas to blob conversion. It calls the provided callback function with the created blob as argument.
+```js
+// 80x60px GIF image (color black, base64 data):
+var b64Data = 'R0lGODdhUAA8AIABAAAAAP///ywAAAAAUAA8AAACS4SPqcvtD6' +
+ 'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
+ 'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7',
+ imageUrl = 'data:image/gif;base64,' + b64Data,
+ blob = window.dataURLtoBlob && window.dataURLtoBlob(imageUrl);
+```
## License
The JavaScript Canvas to Blob script is released under the [MIT license](http://www.opensource.org/licenses/MIT).
View
107 canvas-to-blob.js
@@ -1,5 +1,5 @@
/*
- * JavaScript Canvas to Blob 1.0.1
+ * JavaScript Canvas to Blob 2.0
* https://github.com/blueimp/JavaScript-Canvas-to-Blob
*
* Copyright 2012, Sebastian Tschan
@@ -15,71 +15,56 @@
/*jslint nomen: true, regexp: true */
/*global window, atob, ArrayBuffer, Uint8Array, define */
-(function ($) {
+(function (window) {
'use strict';
-
- var BlobBuilder = window.MozBlobBuilder ||
- window.WebKitBlobBuilder || window.BlobBuilder,
- blobTypes = /^image\/(jpeg|png)$/,
-
- // Converts a canvas element to a Blob or File object:
- canvasToBlob = function (canvas, callback, options) {
- options = options || {};
- if (canvas.toBlob) {
- canvas.toBlob(callback, options.type);
- return true;
- } else if (canvas.mozGetAsFile) {
- var name = options.name;
- callback(canvas.mozGetAsFile(
- (blobTypes.test(options.type) && name) ||
- ((name && name.replace(/\..+$/, '')) || 'blob') + '.png',
- options.type
- ));
- return true;
- } else if (canvas.toDataURL && BlobBuilder && window.atob &&
- window.ArrayBuffer && window.Uint8Array) {
- callback(canvasToBlob.dataURItoBlob(
- canvas.toDataURL(options.type)
- ));
- return true;
- }
- return false;
- };
-
- // Converts a dataURI to a Blob:
- canvasToBlob.dataURItoBlob = function (dataURI) {
- var byteString,
- arrayBuffer,
- intArray,
- i,
- bb,
- mimeString;
- if (dataURI.split(',')[0].indexOf('base64') >= 0) {
- // Convert base64 to raw binary data held in a string:
- byteString = atob(dataURI.split(',')[1]);
- } else {
- // Convert base64/URLEncoded data component to raw binary data:
- byteString = decodeURIComponent(dataURI.split(',')[1]);
+ var CanvasPrototype = window.HTMLCanvasElement &&
+ window.HTMLCanvasElement.prototype,
+ BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
+ window.MozBlobBuilder,
+ dataURLtoBlob = BlobBuilder && window.atob && window.ArrayBuffer &&
+ window.Uint8Array && function (dataURI) {
+ var byteString,
+ arrayBuffer,
+ intArray,
+ i,
+ bb,
+ mimeString;
+ if (dataURI.split(',')[0].indexOf('base64') >= 0) {
+ // Convert base64 to raw binary data held in a string:
+ byteString = atob(dataURI.split(',')[1]);
+ } else {
+ // Convert base64/URLEncoded data component to raw binary data:
+ byteString = decodeURIComponent(dataURI.split(',')[1]);
+ }
+ // Write the bytes of the string to an ArrayBuffer:
+ arrayBuffer = new ArrayBuffer(byteString.length);
+ intArray = new Uint8Array(arrayBuffer);
+ for (i = 0; i < byteString.length; i += 1) {
+ intArray[i] = byteString.charCodeAt(i);
+ }
+ // Write the ArrayBuffer to a blob:
+ bb = new BlobBuilder();
+ bb.append(arrayBuffer);
+ // Separate out the mime component:
+ mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
+ return bb.getBlob(mimeString);
+ };
+ if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {
+ if (CanvasPrototype.mozGetAsFile) {
+ CanvasPrototype.toBlob = function (callback, type) {
+ callback(this.mozGetAsFile('blob', type));
+ };
+ } else if (CanvasPrototype.toDataURL && dataURLtoBlob) {
+ CanvasPrototype.toBlob = function (callback, type) {
+ callback(dataURLtoBlob(this.toDataURL(type)));
+ };
}
- // Write the bytes of the string to an ArrayBuffer:
- arrayBuffer = new ArrayBuffer(byteString.length);
- intArray = new Uint8Array(arrayBuffer);
- for (i = 0; i < byteString.length; i += 1) {
- intArray[i] = byteString.charCodeAt(i);
- }
- // Write the ArrayBuffer to a blob:
- bb = new BlobBuilder();
- bb.append(arrayBuffer);
- // Separate out the mime component:
- mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
- return bb.getBlob(mimeString);
- };
-
+ }
if (typeof define !== 'undefined' && define.amd) {
define(function () {
- return canvasToBlob;
+ return dataURLtoBlob;
});
} else {
- $.canvasToBlob = canvasToBlob;
+ window.dataURLtoBlob = dataURLtoBlob;
}
}(this));
View
2  canvas-to-blob.min.js
@@ -1 +1 @@
-(function(a){"use strict";var b=window.MozBlobBuilder||window.WebKitBlobBuilder||window.BlobBuilder,c=/^image\/(jpeg|png)$/,d=function(a,e,f){f=f||{};if(a.toBlob)return a.toBlob(e,f.type),!0;if(a.mozGetAsFile){var g=f.name;return e(a.mozGetAsFile(c.test(f.type)&&g||(g&&g.replace(/\..+$/,"")||"blob")+".png",f.type)),!0}return a.toDataURL&&b&&window.atob&&window.ArrayBuffer&&window.Uint8Array?(e(d.dataURItoBlob(a.toDataURL(f.type))),!0):!1};d.dataURItoBlob=function(a){var c,d,e,f,g,h;a.split(",")[0].indexOf("base64")>=0?c=atob(a.split(",")[1]):c=decodeURIComponent(a.split(",")[1]),d=new ArrayBuffer(c.length),e=new Uint8Array(d);for(f=0;f<c.length;f+=1)e[f]=c.charCodeAt(f);return g=new b,g.append(d),h=a.split(",")[0].split(":")[1].split(";")[0],g.getBlob(h)},typeof define!="undefined"&&define.amd?define(function(){return d}):a.canvasToBlob=d})(this);
+(function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder,d=c&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,d,e,f,g,h;a.split(",")[0].indexOf("base64")>=0?b=atob(a.split(",")[1]):b=decodeURIComponent(a.split(",")[1]),d=new ArrayBuffer(b.length),e=new Uint8Array(d);for(f=0;f<b.length;f+=1)e[f]=b.charCodeAt(f);return g=new c,g.append(d),h=a.split(",")[0].split(":")[1].split(";")[0],g.getBlob(h)};a.HTMLCanvasElement&&!b.toBlob&&(b.mozGetAsFile?b.toBlob=function(a,b){a(this.mozGetAsFile("blob",b))}:b.toDataURL&&d&&(b.toBlob=function(a,b){a(d(this.toDataURL(b)))})),typeof define!="undefined"&&define.amd?define(function(){return d}):a.dataURLtoBlob=d})(this);
View
2  package.json
@@ -1,6 +1,6 @@
{
"name": "blueimp-canvas-to-blob",
- "version": "1.0.1",
+ "version": "2.0.0",
"title": "JavaScript Canvas to Blob",
"description": "JavaScript Canvas to Blob is a function to convert canvas elements into Blob objects.",
"keywords": [
View
67 test/test.js
@@ -1,5 +1,5 @@
/*
- * JavaScript Canvas to Blob Test 1.0
+ * JavaScript Canvas to Blob Test 2.0
* https://github.com/blueimp/JavaScript-Canvas-to-Blob
*
* Copyright 2012, Sebastian Tschan
@@ -11,7 +11,7 @@
/*global window, describe, it, expect, Blob */
-(function (expect, canvasToBlob) {
+(function (expect) {
'use strict';
// 80x60px GIF image (color black, base64 data):
@@ -19,75 +19,48 @@
'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7',
imageUrl = 'data:image/gif;base64,' + b64Data,
- blob = canvasToBlob.dataURItoBlob(imageUrl);
+ blob = window.dataURLtoBlob && window.dataURLtoBlob(imageUrl);
- describe('canvasToBlob', function () {
-
- it('Returns true when supporting canvas to blob conversions', function (done) {
- window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
- function () {
- done();
- }
- )).to.be.ok();
- }, {canvas: true});
- });
-
- it('Returns false when not supporting canvas to blob conversions', function () {
- expect(canvasToBlob(
- {},
- function () {}
- )).to.not.be.ok();
- });
+ describe('canvas.toBlob', function () {
it('Converts a canvas element to a blob and passes it to the callback function', function (done) {
window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
+ canvas.toBlob(
function (newBlob) {
done();
expect(newBlob).to.be.a(Blob);
- },
- blob
- )).to.be.ok();
+ }
+ );
}, {canvas: true});
});
it('Converts a canvas element to a PNG blob', function (done) {
window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
+ canvas.toBlob(
function (newBlob) {
done();
expect(newBlob.type).to.be('image/png');
},
- {
- type: 'image/png'
- }
- )).to.be.ok();
+ 'image/png'
+ );
}, {canvas: true});
});
it('Converts a canvas element to a JPG blob', function (done) {
window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
+ canvas.toBlob(
function (newBlob) {
done();
expect(newBlob.type).to.be('image/jpeg');
},
- {
- type: 'image/jpeg'
- }
- )).to.be.ok();
+ 'image/jpeg'
+ );
}, {canvas: true});
});
it('Keeps the aspect ratio of the canvas image', function (done) {
window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
+ canvas.toBlob(
function (newBlob) {
window.loadImage(newBlob, function (img) {
done();
@@ -95,14 +68,13 @@
expect(img.height).to.be(canvas.height);
});
}
- )).to.be.ok();
+ );
}, {canvas: true});
});
it('Keeps the image data of the canvas image', function (done) {
window.loadImage(blob, function (canvas) {
- expect(canvasToBlob(
- canvas,
+ canvas.toBlob(
function (newBlob) {
window.loadImage(newBlob, function (newCanvas) {
var canvasData = canvas.getContext('2d')
@@ -114,13 +86,10 @@
expect(canvasData.height).to.be(newCanvasData.height);
}, {canvas: true});
}
- )).to.be.ok();
+ );
}, {canvas: true});
});
});
-}(
- this.expect,
- this.canvasToBlob
-));
+}(this.expect));
Please sign in to comment.
Something went wrong with that request. Please try again.