js 将网络图片格式转为base64 canvas 跨域

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var dataURL = canvas.toDataURL("image/png"); // 可选其他值 image/jpeg
  return dataURL;
}

function main(src, cb) {
  var image = new Image();
  image.src = src + '?v=' + Math.random(); // 处理缓存
  image.crossOrigin = "*"; // 支持跨域图片
  image.onload = function(){
    var base64 = getBase64Image(image);
    cb && cb(base64);
  }
}
main('网络图片地址', function(base64){
  console.log(base64,'是否成功打印base64');
});

posted on 2018-11-28 19:13  老虎念大悲咒  阅读(1255)  评论(0编辑  收藏  举报