title: Cache image files in base64 with jQuery
body: <p>I am trying to write a cache for image files I am working with. I will use this image files to extract parts of the image using canvas.
  But it seems not to work right. If i call the function the first time for an url (empty cache) <code>getBase64OfSubImage</code> returns the wrong sub-image (empty png). But it seems that it just happens sometimes.
  When I run the same command the second time, it returns the correct sub-image.</p>
  
  <pre><code>var backgroundImageURLs = Object();
  
  function checkBase64OfImage(url){
      var dfd = $.Deferred();
  
      if(backgroundImageURLs[url] !== undefined){
          dfd.resolve();
      }
      else {
          var req = new XMLHttpRequest();
          req.overrideMimeType('text/plain; charset=x-user-defined');
          req.open('GET', url, true);
          req.responseType = 'arraybuffer';
          req.onload = function() {
              buffer = req.mozResponseArrayBuffer || req.response;
              type = req.getResponseHeader('Content-Type');
  
              var blob = new Blob([buffer], {type: type});
              var fr = new FileReader();
              fr.onload = function() {
                  backgroundImageURLs[url] = window.btoa(fr.result);
                  dfd.resolve();
              };
              fr.readAsBinaryString(blob);
          };
          req.send(null);
      }
  
      return dfd.promise();
  }
  
  function getBase64OfSubImage(url, pos, size){
      if(backgroundImageURLs[url] !== undefined){
          var base64_img = "data:image/png;base64,"+backgroundImageURLs[url];
          var tmp_img = new Image();
          tmp_img.setAttribute("src", base64_img);
  
          var canvas = $('&lt;canvas/&gt;')[0];
          canvas.width = size[0];
          canvas.height = size[1];
  
          canvas.getContext('2d').drawImage(tmp_img, pos[0], pos[1], size[0], size[1], 0, 0, size[0], size[1]);
          return canvas.toDataURL().split(",")[1]; //Get Base64-representation of partial image
      }
      return false;
  }
  </code></pre>
  
  <p>Any idea why it is not working as aspected? I use jQuery Deferred/When to make sure the image is fully loaded into my cache:</p>
  
  <pre><code>$.when(checkBase64OfImage(background_url)).then(function(){
      img_b64 = getBase64OfSubImage(background_url, background_position, size);
  }
  </code></pre>