Subversion Repositories munaweb

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
/**
2
 * Converts an image to a dataURL
3
 * @param  {String}   src          The src of the image
4
 * @param  {Function} callback
5
 * @param  {String}   outputFormat [outputFormat='image/png']
6
 * @url   https://gist.github.com/HaNdTriX/7704632/
7
 * @docs  https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods
8
 * @author HaNdTriX
9
 * @example
10
 *
11
 *   toDataUrl('http://goo.gl/AOxHAL', function(base64Img){
12
 *     console.log('IMAGE:',base64Img);
13
 *   })
14
 *
15
 */
16
function toDataUrl(src, callback, outputFormat) {
17
  // Create an Image object
18
  var img = new Image();
19
  // Add CORS approval to prevent a tainted canvas
20
  img.crossOrigin = 'Anonymous';
21
  img.onload = function() {
22
    // Create an html canvas element
23
    var canvas = document.createElement('CANVAS');
24
    // Create a 2d context
25
    var ctx = canvas.getContext('2d');
26
    var dataURL;
27
    // Resize the canavas to the original image dimensions
28
    canvas.height = this.naturalHeight;
29
    canvas.width = this.naturalWidth;
30
    // Draw the image to a canvas
31
    ctx.drawImage(this, 0, 0);
32
    // Convert the canvas to a data url
33
    dataURL = canvas.toDataURL(outputFormat);
34
    // Return the data url via callback
35
    callback(dataURL);
36
    // Mark the canvas to be ready for garbage
37
    // collection
38
    canvas = null;
39
  };
40
  // Load the image
41
  img.src = src;
42
  // make sure the load event fires for cached images too
43
  if (img.complete || img.complete === undefined) {
44
    // Flush cache
45
    img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
46
    // Try again
47
    img.src = src;
48
  }
49
}