I have the following code:
let v = new Vibrant("https://source.unsplash.com/random/");
var bodyS = document.getElementsByTagName('body')[0].style;
bodyS.background = 'url('+v._src+') no-repeat center center fixed';
Is there a way to save the image sent by unsplash to a variable so I can set it to the bg as well as use it for the following script instead of using this url again because unsplash sends a unique picture through the url everytime.
As some comments already suggest, you can use fetch
+createObjectURL
to be able to re-use a single image. This snippet shows 4 random images at start (though the links had to be made unique, otherwise they would end up being the same because of caching). When you click the button however, it fetches a single new image and explicitly applies it to all the four <img>
elements. The commented part would also replace the button and actually download the image on a second click, just the sandbox here on StackOverflow simply doesn't allow downloads.
async function doThing(){
let image=await fetch("https://source.unsplash.com/random/").then(res=>res.blob());
let url=URL.createObjectURL(image);
for(let img of document.getElementsByTagName("img"))
img.src=url;
// let a=document.createElement("a");
// a.href=url;
// a.download="test.jpg";
// let button=document.getElementsByTagName("button")[0];
// button.innerText="Download";
// button.onclick=()=>a.click();
}
img{
width:20%;
}
<img src="https://source.unsplash.com/random/?1">
<img src="https://source.unsplash.com/random/?2">
<img src="https://source.unsplash.com/random/?3">
<img src="https://source.unsplash.com/random/?4">
<br>
<button onclick="doThing()">Clicky</button>
(If you want to test it elsewhere, a simple way to grab the code is to run the snippet, then right-click on some empty spot inside the frame, and use "View frame source" in Chrome, or "This Frame"/"View Frame Source" in Firefox)