一开始考虑使用a标签的download属性进行下载:
1
2
3
|
< a href = "图片src" download = "下载海报" > 下载海报 </ a > |
但是通过测试,发现再safari中,下载的文件不能带上拓展名,所以只好换一个思路,使用canvas进行处理。
1.图片需要添加crossOrigin=’anonymous’设置图像的跨域属性
1
|
img.crossOrigin = 'anonymous' ; |
2.使用toDataURL把图片转换成base64格式
1
|
canvas.toDataURL( "image/png" ) |
3.使用模拟点击事件,触发下载
1
2
3
4
5
6
7
|
var save_link = document.createElement( 'a' ); save_link.href = image; save_link.download = '测试.png' ; var clickevent = document.createEvent( 'MouseEvents' ); clickevent.initEvent( 'click' , true , false ); save_link.dispatchEvent(clickevent); |
完整代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
var canvas = $( '.canvas' ); var cxt = canvas[0].getContext( "2d" ); function save(){ var img = new Image(); img.crossOrigin = 'anonymous' ; img.onload = function (){ var _w = img.naturalWidth; var _h = img.naturalHeight; canvas.attr({width:_w,height:_h}); cxt.drawImage(img,0,0); var image = canvas[0].toDataURL( "image/png" ) var save_link = document.createElement( 'a' ); save_link.href = image; save_link.download = '测试.png' ; var clickevent = document.createEvent( 'MouseEvents' ); clickevent.initEvent( 'click' , true , false ); save_link.dispatchEvent(clickevent); }; img.src = 'http://n.sinaimg.cn/sports/transform/20170825/NZI3- fykiufe6650492.jpg' ; } |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容