CANVAS中使用跨域图片转base64图片时报错处理:
function getBase64(imgUrl) {
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", imgUrl, true);
// 至关重要
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
//得到一个blob对象
var blob = this.response;
// console.log("blob", blob)
// 一:使用 base64 图片
// let oFileReader = new FileReader();
// oFileReader.onloadend = function(e) {
// let base64 = e.target.result;
// bgimgSrc = base64;
// console.log(bgimgSrc);
// };
// oFileReader.readAsDataURL(blob);
// 二:使用 blob 图片
let src;
if(window.createObjectURL!=undefined){
src = window.createObjectURL(blob);
}else if (window.URL!=undefined){
src = window.URL.createObjectURL(blob);
}else if (window.webkitURL!=undefined){
src = window.webkitURL.createObjectURL(blob);
}
bgimgSrc = src;
console.log(bgimgSrc);
}
}
xhr.send();
}
使用:
getBase64('图片URL');
来源:oschina
链接:https://my.oschina.net/u/4270922/blog/3225230