Reputation: 23
I tried to get random images from unsplash api by given code below, now i am looking for to way to DOWNLOAD displayed image from that Api
const numItemsToGenerate = 1;
function renderItem(){
fetch(`https://source.unsplash.com/920x720?
beach`).then((response)=> {
let item = document.getElementById('container');
item.innerHTML = `
<img class="beach_image" src="${response.url}"
alt="beach image"/>
`
})
}
for(let i=0;i<numItemsToGenerate;i++){
renderItem();
}
Upvotes: 1
Views: 965
Reputation: 5084
I have created a function, that downloads the image from the unsplash. But the problem is, it doesn't work on Stackoverflow's snippet, since is creates null
blob URL. You need to run this program on a server (like localhost
), in order to work.
Try it on - https://jsfiddle.net/xt5wb2vn/
HTML
<div id="container">
</div>
<button class="download">Click to download</button>
JavaScript
const numItemsToGenerate = 1;
function downloadImage(url) {
let a = document.createElement("a");
a.href = url;
a.download = 'image.jpg';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function renderItem() {
fetch(`https://source.unsplash.com/920x720?beach`)
.then(resp => resp.blob())
.then(image => {
const image_url = URL.createObjectURL(image)
let item = document.getElementById('container');
item.innerHTML = `<img class="beach_image" src="${image_url}" alt="beach image"/>`;
return image_url;
}).then(url=>document.querySelector(".download").onclick = ()=>downloadImage(url))
}
renderItem()
Upvotes: 1
Reputation: 1006
Use URL.createObjectURL
So, the function should look like
fetch(`https://source.unsplash.com/920x720?beach`)
.then(resp => resp.blob())
.then(image => {
const image_url = URL.createObjectURL(image)
const item = document.getElementById('container')
item.src = image_url
})
Upvotes: 1