<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS实现点击图片时将图片下载在本地</title>
</head>
<body>
<img class="lazyload" data-original="https://bbs.oddfox.cn/view/img/logo.png" alt="" onclick="downloadIamge("img","自行车女孩")">
<script>
function downloadIamge(selector, name){
// 创建一个img标签
var image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute("crossOrigin", "anonymous");
image.onload = function(){
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height)
var url = canvas.toDataURL("image/png");
// 生成一个a元素
var a = document.createElement("a");
// 创建一个单击事件
var event = new MouseEvent("click");
// 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称
a.download = name || "one"; // one是默认的名称
// 将生成的URL设置为a.href属性
a.href = url;
// 触发a的单击事件
a.dispatchEvent(event);
}
image.src = document.querySelector(selector).src;
}
</script>
</body>
</html>