关键还是要通过canvas对象的toDataURL方法去实现
<div id="showme"></div>
let imgSrc = "https://cdnpw.chinaesport.com/kdhxoi/storage/emulated/0/tencent/MicroMsg/WeiXin/mmexport1592366797764.webp";
//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
function getBase64Image(img, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
return dataURL; //返回base64
}
function getCanvasBase64(img) {
var image = new Image();
//至关重要
image.crossOrigin = '';
image.src = img;
//至关重要
var deferred = $.Deferred();
if (img) {
image.onload = function () {
console.log(image) //将<img crossorigin="" src="xx.webp">值传给canvas处理
deferred.resolve(getBase64Image(image));//将base64传给done上传处理
}
return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
}
}
//调用
getCanvasBase64(imgSrc)
.then(function (base64) {
// 这里拿到的是转换后的base64地址,可以做其他操作
// console.log("方式二》》》》》》》》》",base64);
$('<img src="'+base64+'">').appendTo('#showme')
}, function (err) {
console.log(err);
});