具體思路:
- 通過圖片路徑獲取圖片資源。
- 將圖片資源使用canvas轉(zhuǎn)為base64
- 再將base64轉(zhuǎn)換為
Blob對象此處將base64 轉(zhuǎn)換為 Blob 是為了解決低版本的Firefox瀏覽器中得到的 base64 數(shù)據(jù)為一個(gè)空白圖片的bug
- 使用
URL.createObjectURL()方法將Blob轉(zhuǎn)化為路徑 - 通過
<a>標(biāo)簽觸發(fā)點(diǎn)擊事件實(shí)現(xiàn)下載
具體代碼如下:
function downPicture(src){
const image = new Image();
const pos = src.lastIndexOf('\/'); // 查找最后一個(gè)/的位置
const fileName = src.substring(pos + 1);
// 解決跨域 Canvas 污染問題
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
const imgData = canvas.toDataURL({format: 'png', multiplier: 4}); // 得到圖片的base64編碼數(shù)據(jù)
// 此處又將base64轉(zhuǎn)為Blob 對象是因?yàn)椋涸诘桶姹镜腇irefox瀏覽器中得到的 base64 數(shù)據(jù)為一個(gè)空白圖片
// 所以才轉(zhuǎn)為Blob對象,解決此bug。不考慮兼容性可以直接將此base64對象直接賦值給a.href即可。無需以下***中操作
// *********************************************
const blob = dataURLtoBlob(imgData);
const objurl = URL.createObjectURL(blob);
// *********************************************
const a = document.createElement('a'); // 生成一個(gè)a元素
const e = new MouseEvent('click'); // 創(chuàng)建一個(gè)單擊事件
a.download = fileName ; // 設(shè)置圖片名稱
a.href = objurl; // 將生成的URL設(shè)置為a.href屬性
a.dispatchEvent(e); // 觸發(fā)a的單擊事件
};
image.src = src;
}
function dataURLtoBlob(dataurl){
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
}