Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Created April 6, 2020 05:17
Show Gist options
  • Save wobsoriano/e05ced7fd464e559e5042449e96c3b79 to your computer and use it in GitHub Desktop.
Save wobsoriano/e05ced7fd464e559e5042449e96c3b79 to your computer and use it in GitHub Desktop.
Download external image on button click
function downloadImage(data, filename = 'untitled.jpeg') {
var a = document.createElement('a');
a.href = data;
a.download = filename;
document.body.appendChild(a);
a.click();
}
document.getElementById('btn-download').addEventListener("click", function(e) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = '';
img.src = "https://robohash.org/robert"
img.onload = function() {
const img = this;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
const dataURL = canvas.toDataURL();
downloadImage(dataURL, 'my-canvas.jpeg');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment