title: Function that returns the data URI Base64 string of image in Javascript
body: <p>I'm really struggling to write a function for getting the Base64 encoding of an image. Since this function will be part of a bigger script that uses jsPDF.js to make PDFs on-the-fly from a website, It's important the be able to calculate those Base64 encodings as the result of a function. The images will be hosted on the same server, so no same-origin issues. I know the <strong>.toDataURL()</strong> method of the canvas element can do this and I also know that the image needs to be fully loaded in order to get the Data URL correctly, so I wrote this function</p>
  
  <pre><code>// Encode image to Base64
  function encodeBase64(url, format)
  {
      var image = new Image(),
      canvas = document.createElement("canvas"),
      context = canvas.getContext("2d");
      image.src = url;
      image.onload = function ()
      {
          canvas.width = image.width;
          canvas.height = image.height;
          context.drawImage(image, 0, 0, image.width, image.height);
          var dataURL = canvas.toDataURL(format);
          alert(dataURL);
      };
  }
  </code></pre>
  
  <p>The problem is that I don't know how to "extract" the dataURL value from the onload function so that the encodeBase64 function simply returns that value and I can put it in an array. Alert returns that string correctly so I'm sure the code works, but if I try to write any other statement like "return dataURL" or similar I just get <strong>undefined</strong> value. Please help.</p>