背景:一般使用a标签,但浏览器有时候不会下载,会打开新的标签页,很不友好

下面这段代码可以实现浏览器下载图片

 1 function downPic(src,imgName) {
 2         var canvas = document.createElement('canvas');
 3         var img = document.createElement('img');
 4         img.onload = function(e) {
 5             canvas.width = img.width;
 6             canvas.height = img.height;
 7             var context = canvas.getContext('2d');
 8             context.drawImage(img, 0, 0, img.width, img.height);
 9             canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
10             canvas.toBlob((blob) => {
11                     var link = document.createElement('a');
12                     link.href = window.URL.createObjectURL(blob);
13                     link.download = imgName;
14                     link.click();
15                 },
16                 "image/jpeg");
17         };
18         img.crossOrigin = "Anonymous";
19         img.src = src;
20     }
View Code

 

posted on 2019-03-20 09:50  cigarlau  阅读(624)  评论(0编辑  收藏  举报