Here Example of How to download image on Button Click
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<img src="https://i.imgur.com/sduLRvf.jpg" alt="">
<button>Download</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
CSS:
div {
display: flex;
flex-direction: column;
align-items: center;
}
img {
height: 400px;
width: 400px;
}
button {
display: block;
padding: 10px;
margin-top: 10px;
}
JavaScript:
let btnDownload = document.querySelector('button');
let img = document.querySelector('img');
btnDownload.addEventListener('click', () => {
let imagePath = img.getAttribute('src');
let fileName = getFileName(imagePath);
saveAs(imagePath, fileName);
});
function getFileName(str) {
return str.substring(str.lastIndexOf('/') + 1)
}
Result:
Source Code: https://codepen.io/er-gaurav-dixit/pen/OJpEdrr