使用javascript将图像转换为base64

时间:2014-07-20 15:59:51

标签: javascript html canvas

 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);

警报(dataURL)没有显示任何结果。那里没有生成弹出窗口?怎么解决这个?
那有什么不妥?

1 个答案:

答案 0 :(得分:1)

存在交叉原点问题...尝试使用此功能

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; 
    };
}

我删除了上下文,并以不同的方式加载了图像