title: Canvas to data url not working properly
body: <p>I have a function that takes an img-element and returns a data url. This works like 7/10 times and returns a blank image 3/10 times. I view the created data url through my browser(chrome) and use the same images so I know that this function is returning broken images. Can anyone spot why?</p>
  
  <pre><code>function imgToDataURL(img) {
      var canvas = document.createElement('canvas');
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;
      var c = canvas.getContext('2d');
      c.drawImage(img, 0, 0);
      dataurl = canvas.toDataURL();
      return dataurl;
  }
  
  $(function() {
      img = new Image();
      img.crossOrigin = '';
      img.onload = function() {
          newimg = new Image();
          newimg.onload = function() {
              document.body.appendChild(newimg);
          }
          newimg.src = imgToDataURL(img);
      }
      img.src = 'https://somedomain.s3.amazonaws.com/someimg.png';
  });
  </code></pre>
  
  <p>This example works most of the time but sometimes ends with a large white rectangle instead of the image.</p>