代码实现
// canvas 下载图片
function downImg(src, name, ext){
const img = new Image();
img.src = src;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
const cvs = document.createElement('canvas');
cvs.width = img.width;
cvs.height = img.height;
cvs.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
const a = document.createElement('a');
a.href = cvs.toDataURL(`image/${ext}`);
a.download = `${name}`;
a.click()
}
}
使用
const imgInp = document.querySelector('.downImg');
const imgDownBtn = document.querySelector('.downImgBtn')
const select = document.getElementsByTagName('select')[0]
const nameInp = document.querySelector('.downImgName');
function handleDownload(){
if(!imgInp.value){
alert('请先输入要下载图片的地址')
return
}
downImg(imgInp.value, nameInp.value, select.value)
}
imgDownBtn.addEventListener('click', handleDownload)
本文链接:https://blog.smallhao.fun/?id=21 转载需授权!
暂无评论
发表评论