原文链接: link.
说明:此写法在taro、react项目里无效,new Image()在此打印为标签,虚拟dom打印为普通对象,不会触发onload或者onLoad方法,在标签setstate触发canvas写法也会报错图片不完整,还没找到正确写法
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>图片路径转成base64</title>
</head>
<body>
<script>
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
//var img = "http://127.0.0.1/base64/1.jpg";
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 ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var image = new Image();
image.crossOrigin = '';
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
console.log('image', image)
</script>
</body>
</html>