有没有小伙伴在开发“纯前端下载图片”性能时,遇到以下的场景?
1. 下载已存在的图片
2. 下载某个元素的内容
分享解决以上问题的办法
- 下载已存在的图片:应用 canvas 画图,a 标签下载
export function downloadImg(imgUrl: string, imgTitle: string) {var img = new Image();
img.src = imgUrl;
// 必须设置,否则 canvas 中的内容无奈转换为 blob
img.setAttribute('crossOrigin', 'Anonymous');
img.onload = function () {var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
let ctx: any = canvas.getContext('2d');
// 将 img 中的内容画到画布上
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// 将画布内容转换为 Blob
canvas.toBlob(blob => {
// blob 转为同源 url
var blobUrl = window.URL.createObjectURL(blob);
// 创立 a 链接
var a = document.createElement('a');
a.href = blobUrl;
a.download = imgTitle || '下载图片'; // 设置图片名称
// 触发 a 链接点击事件,浏览器开始下载文件
a.click();});
};
}
-
下载某个元素的内容:应用 html2canvas 插件进行截图,a 标签下载
官网:http://html2canvas.hertzen.com/// 引入 html2canvas import html2canvas from 'html2canvas'; // 下载凭证按钮 const downLoadBtn = () => { // 获取 dom 节点 const downLoadDom: any = document.getElementById("downLoadDom"); html2canvas(downLoadDom, { width: downLoadDom.offsetWidth, height: downLoadDom.offsetHeight, scale: 2, }).then((canvas) => {const imgBase64 = canvas.toDataURL('image/png'); downLoadMethod(imgBase64); }); } // 下载图片 const downLoadMethod = (url: any) => {var oA = document.createElement("a"); oA.download = '下载图片'; oA.href = url; oA.className = "downLoad" document.body.appendChild(oA); oA.click(); oA.remove();}
留神📢
- html2canvas 图片跨域问题,可参考文档
https://blog.csdn.net/qq_3890…
附送
-
将 base64 图片转化为 formData 并上传办法
// 将 base64 图片转化为 formData 并上传 export async function transferBase64ToImg(base64String: any) {var bytes = window.atob(base64String.split(',')[1]); var array = []; for (var i = 0; i < bytes.length; i++) {array.push(bytes.charCodeAt(i)); } var blob = new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); var formData = new FormData(); formData.append('file', blob, Date.now() + '.jpg'); let res = await API.edit.uploadImage(formData); return res.fullPath; }