0
 function convertImgToBase64(url){

  var canvas = document.createElement('CANVAS');
  var ctx = canvas.getContext('2d');
  var img = new Image;
  img.crossOrigin = 'Anonymous';
  img.onload = function(){
    canvas.height = img.height;
    canvas.width = img.width;
      ctx.drawImage(img,0,0);
      var dataURL = canvas.toDataURL('image/png',"");
      alert(dataURL);

      canvas = null; 
  };
  img.src = url;



}

var url_to_be_converted = "http://www.google.com/image/sample"
convertImgToBase64(url_to_be_converted);

Alert(dataURL) does not showing any result.No pop up is generated there? How to solve this?
What wrong there?

3
  • missing semicolon? should be var url_to_be_converted = "http://www.google.com/image/sample"; Commented Jul 20, 2014 at 16:08
  • No it's not a problem Commented Jul 20, 2014 at 16:10
  • 1
    @tillz: semicolons are optional in JavaScript, though their omission can cause unexpected problems sometimes. Commented Jul 20, 2014 at 16:39

1 Answer 1

1

There is a cross origin problem ... try using this function

function convertImgToBase64(url)
{
    var canvas = document.createElement('CANVAS');
    img = document.createElement('img'),
    img.src = url;
    img.onload = function()
    {
        canvas.height = img.height;
        canvas.width = img.width;
        var dataURL = canvas.toDataURL('image/png');
        alert(dataURL);
        canvas = null; 
    };
}

I removed the context and I loaded the image in a different way

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.