title: Get image data from HTML element
body: <p>I've come across a few questions here that gave me some hints for a problem I'm currently having, but none seems to actually fit the bill.</p>
  
  <p>I'm currently working with an angular module, ngCropper (<a href="https://github.com/koorgoo/ngCropper" rel="nofollow">https://github.com/koorgoo/ngCropper</a>) which easily deals with images coming from a file input, but I need it to work also with external URLs. In order to work with external URLs I used the suggestion gave by <strong>faheyyy</strong> (<a href="https://github.com/koorgoo/ngCropper/issues/3" rel="nofollow">https://github.com/koorgoo/ngCropper/issues/3</a>) but now I'm dealing with CORS issues and there's no way I can do server changes.</p>
  
  <p>So, I was thinking of loading an image on a hidden HTML element and somehow pick up that data, encode it as Base64 and then I'd be able to use it on the cropper module without needing to create a new GET request (which will create the CORS problem).
  I've also tried creating a directive that reads the source of an image (the directive is inserted on the <em>img</em> element) and tries putting it on a canvas element, and there gets the dataURL:</p>
  
  <pre><code>.directive('toBase64', function ($document) {
      return {
          restrict : 'A',
          link : function (scope, element, attr) {
  
            element.on('load', function () {
              getBase64Image(element);
            });
  
            function getBase64Image(element) {
              var theImage = new Image();
              theImage.src = element.attr("src");
              var imageWidth = theImage.width;
              var imageHeight = theImage.height;
  
              var canvas = element.siblings('#cropCanvas');
              canvas.width = imageWidth;
              canvas.height = imageHeight;
              var ctx = canvas.getContext("2d");
              ctx.drawImage(element, 0, 0);
              var dataURL = canvas.toDataURL("image/png");
              return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
            }
          }
      };
  });
  </code></pre>
  
  <p>The directive is still in works, but I'm running into problems with the <strong>canvas.getContext("2d")</strong> line (it throws <em>undefined</em>).</p>
  
  <p>So far, the threads/answers I found here already deal with the image <em>src</em> being passed as Base64, but I also need it to be working with URLs, and I can't move past this.
  Could someone, please point me into the right direction?
  Thank you </p>