Last active
October 31, 2018 20:06
-
-
Save HaNdTriX/aa23ed3b8c9c50699174 to your computer and use it in GitHub Desktop.
Convert an imageURL to a base64 dataURL via canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert an imageURL to a | |
* base64 dataURL via canvas | |
* | |
* @param {String} url | |
* @param {Object} options | |
* @param {String} options.outputFormat [outputFormat='image/png'] | |
* @param {Float} options.quality [quality=1.0] | |
* @return {Promise} | |
* @docs https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods | |
* @author HaNdTriX | |
*/ | |
function imgURLToDataURL(url, options = {}) { | |
return new Promise((resolve, reject) => { | |
img = new Image(); | |
img.crossOrigin = 'Anonymous'; | |
img.onload = () => { | |
let canvas = document.createElement('CANVAS'), | |
ctx = canvas.getContext('2d'), | |
dataURL; | |
canvas.height = img.height; | |
canvas.width = img.width; | |
ctx.drawImage(img, 0, 0); | |
dataURL = canvas.toDataURL(options.outputFormat, options.quality); | |
resolve(dataURL); | |
canvas = null; | |
}; | |
img.src = url; | |
}); | |
} |
Compiled to ES5
/**
* Convert an imageURL to a
* base64 dataURL via canvas
*
* @param {String} url
* @param {Object} options
* @param {String} options.outputFormat [outputFormat='image/png']
* @param {Float} options.quality [quality=1.0]
* @return {Promise}
* @docs https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods
* @author HaNdTriX
*/
'use strict';
function imgURLToDataURL(url) {
var options = arguments[1] === undefined ? {} : arguments[1];
return new Promise(function (resolve, reject) {
img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(options.outputFormat, options.quality);
resolve(dataURL);
canvas = null;
};
img.src = url;
});
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: