title: Return dataURL from canvas without using a callback
body: <p>I am trying to convert an img URL to a var that I can use elsewhere in my code. </p>
  
  <p>So far, I have the following approach:</p>
  
  <pre><code>function toDataUrl(src) {
    // Create an Image object
    var img = new Image();
    // Add CORS approval to prevent a tainted canvas
    img.crossOrigin = 'Anonymous';
    // Load the image
    img.src = src;
    // make sure the load event fires for cached images too
    if (img.complete || img.complete === undefined) {
      // Flush cache
      img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
      // Try again
      img.src = src;
    }
  
    img.onload = function() {
      // Create an html canvas element
      var canvas = document.createElement('CANVAS');
      // Create a 2d context
      var ctx = canvas.getContext('2d');
      var dataURL;
      // Resize the canavas to the original image dimensions
      canvas.height = this.naturalHeight;
      canvas.width = this.naturalWidth;
      // Draw the image to a canvas
      ctx.drawImage(this, 0, 0);
      // Convert the canvas to a data url
      dataURL = canvas.toDataURL(outputFormat);
      // Mark the canvas to be ready for garbage
      // collection
      canvas = null;
  
      // Return the data url via callback
      // callback(dataURL);
      return dataURL;
  
    };
  }
  
  var myimg = toDataUrl('/media/signatures/signature.8.png');
  </code></pre>
  
  <p>However, <code>myimg</code> returns <code>undefined</code>. I think this is because it might be loading asynchronously. I have refered to <a href="https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call">this answer</a> however it does not explain how to set the callback as a global variable. </p>
  
  <p>How can I set <code>myimg = dataURL</code>? Is there a way to do this without a callback?</p>