Recent projects need to implement a function to download the picture (as shown below)
I began to consider using a download attribute a label to download:
<a href="图片src" download="下载海报">
下载海报
</a>
But by testing, we found another safari, the downloaded file can not bring the name to expand, so I had to change a line of thought, using canvas for processing.
1. The image needs to add crossOrigin = 'anonymous' arranged cross-domain image properties
img.crossOrigin = 'anonymous';
2. Use toDataURL the picture is converted to base64 format
canvas.toDataURL("image/png")
3. Use the Click event simulation, triggering download
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);
Complete code:
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';
}