提问者:小点点

获取图像的宽度和高度。src是代理


我有一个Vue组件,在它里面我有一个img,我需要得到图像尺寸,最好是在显示图像之前(通过宽度或高度来适应容器)。

this.img = new Image();
this.img.src = this.payload.src;
this.img.onload = () => {
  let width = this.img.naturalWidth;
  let height = this.img.naturalHeight;
}

该代码可能无法工作,映像src可以返回401(还不确定),我们使用代理并从服务器上的存储桶中获取该文件。比如/api/getStorageResource?斑点=

我能做什么呢?

有了链接,我可以通过axios获取图像并将其设置为元素,而不是

作为一个选项,我看到我可能拥有现在的元素


共1个答案

匿名用户

您可以使用async/wait和在try/cat块中获取api的组合来从您的服务器获取图像URL,然后您可以继续创建

在下面的示例代码段中,我添加了一个按钮,该按钮将在单击时将图像添加到容器中,这样您就可以在DOM上呈现图像之前看到容器如何具有检索到的图像维度:

const imgDiv = document.querySelector('#imgDiv');
const btn = document.querySelector('#imgBtn');

//The fetchImg function will fetch the image URL from the server and log error to console if file not found
const fetchImg = async () => {
  try {
    // replace the following example url with "this.payload.src"
    const imgURL = await fetch('https://picsum.photos/id/237/200/200');
    return imgURL;
  } catch (err) {
      // do something here if image not found
      console.log('Image not found!');
  } 
}

fetchImg().then((res) => {
  // create a new image element with the URL as the src
  const img = new Image();
  img.src = res.url; // change ".url" according to how the data you get from your server is structured

  // assign the retrieved width and height of img to container
  img.addEventListener('load', () => {
    imgDiv.style.width = img.naturalWidth + 'px';
    imgDiv.style.height = img.naturalHeight + 'px';
  });
  
  btn.addEventListener('click', () => imgDiv.appendChild(img));
});
html, body {margin: 0;padding: 10px;width: 100%; height: 100%;text-align: center;}
#imgDiv {background-color: #222;margin: 0 auto;}
<button id="imgBtn">Add Image</button>
<div id="imgDiv"></div>