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