How to upload an image from HTML5 canvas
The Uploader JS API allows you to upload a file from a file object. To upload an image from an HTML5 canvas, you need to do the following:
- Encode a canvas to a blob object.
- Upload this object to Uploadcare via
uploadcare.fileFrom('object', blob);
For example:
canvas.toBlob(function (blob) { var file = uploadcare.fileFrom('object', blob); file.done(function (fileInfo) { // file is uploaded. }); }, 'image/jpeg', 0.9);
Note that canvas.toBlob
is not supported by some browsers. If you’re using an unsupported browser, you might need to use a polyfill to implement this method:
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'} ) ); } }); };