点击按钮下载图片(ie,FF,chrome)

参考网上的一些资料后,总结出来  

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>图片下载</title>
</head>

<body>
<h1>图片下载</h1>
<script>

function downloadImage(){

var CAPTURE_SCREEN_FILE_NAME = 'download.jpeg';//文件名

if(typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob( document.getElementById("kvm").msToBlob() /* Canvas to Blob */,
/* Save file name */ CAPTURE_SCREEN_FILE_NAME );
return;
}

// Works as fall back mechanism, in case of browsers other than IE.
var link = document.createElement('a');
// We wan't to save the canvas to JPEG format. So giving parameter value for toDataURL() method, as "image/jpeg".
// If not mentioned, canvas will be exported as PNG format.
var canvas=document.getElementById('kvm');
var ctx=canvas.getContext('2d');
var img=new Image();
img.src='image/2.jpg';//图片url,可以是本地也可是网络或后端url
img.onload=function () {
ctx.drawImage(img,0,0);
}
link.href = document.getElementById("kvm").toDataURL("image/jpg");
link.download = CAPTURE_SCREEN_FILE_NAME; // Save file name
document.body.appendChild(link); // For Firefox browser
link.click(); // Start Download
link.remove(); // For Firefox browser
}
</script>

<canvas id="kvm"></canvas>
<!--<img id="kvm" src="image/2.jpg" />-->
<input type="button" onclick="downloadImage()" value="下载" />



</body>

</html>
原文地址:https://www.cnblogs.com/yangjiajie/p/7521469.html