从javascript中获取的api下载渲染图像的任何函数

fquxozlt  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(212)

我试图通过下面给定的代码从unsplash api中获取随机图像,现在我正在寻找从该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();
           }
dw1jzc5e

dw1jzc5e1#

我已经创建了一个函数,可以从unsplash下载图像。但问题是,它对stackoverflow的代码段不起作用,因为它创建了 null BlobURL。您需要在服务器上运行此程序(如 localhost ),以便工作。
试穿一下-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()
5f0d552i

5f0d552i2#

使用 URL.createObjectURL 因此,函数应该如下所示

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
  })

相关问题