Canvas实现图片下载功能
摘要:代码实现 // 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.addEven<!--autointro-->...
代码实现
// 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 转载需授权!
Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!