Blame | Last modification | View Log | RSS feed
/*** Converts an image to a dataURL* @param {String} src The src of the image* @param {Function} callback* @param {String} outputFormat [outputFormat='image/png']* @url https://gist.github.com/HaNdTriX/7704632/* @docs https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods* @author HaNdTriX* @example** toDataUrl('http://goo.gl/AOxHAL', function(base64Img){* console.log('IMAGE:',base64Img);* })**/function toDataUrl(src, callback, outputFormat) {// Create an Image objectvar img = new Image();// Add CORS approval to prevent a tainted canvasimg.crossOrigin = 'Anonymous';img.onload = function() {// Create an html canvas elementvar canvas = document.createElement('CANVAS');// Create a 2d contextvar ctx = canvas.getContext('2d');var dataURL;// Resize the canavas to the original image dimensionscanvas.height = this.naturalHeight;canvas.width = this.naturalWidth;// Draw the image to a canvasctx.drawImage(this, 0, 0);// Convert the canvas to a data urldataURL = canvas.toDataURL(outputFormat);// Return the data url via callbackcallback(dataURL);// Mark the canvas to be ready for garbage// collectioncanvas = null;};// Load the imageimg.src = src;// make sure the load event fires for cached images tooif (img.complete || img.complete === undefined) {// Flush cacheimg.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';// Try againimg.src = src;}}