javascript - 获取图像的宽度和高度。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?blob=
我能做些什么?
有了链接,我可以通过 axios 以某种方式获取图像并将其设置为元素,而不是<img src=".." />
作为一个选项,我看到我可能可以拥有现在的元素<img src="/api/getStorageResource?blob=" />
并 getElementById 它并获取宽度和高度......不知道我在这里有什么选择。
解决方案
您可以在try/catch块中使用async/await和fetch api的组合从服务器获取图像 URL,然后您可以继续创建元素,将检索到的图像 URL 分配给 img 元素,最后设置和容器等于 img 元素的宽度和高度。<img>
src
width
height
在下面的示例代码片段中,我添加了一个按钮,该按钮将在单击时将图像添加到容器中,这样即使在图像在 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>
上面代码的 JSFiddle:https ://jsfiddle.net/AndrewL64/2hu3yxtq/104/
推荐阅读
- ssl - Issue connecting to SSL secured Kafka
- django - Django] Saving multiple images by formset doesn't work
- ios - iOS 应用程序的 Citrix MDX 工具包包装失败并出现“Mach Header contains Invalid Flag bits ...”错误
- javascript - JavaScript 二叉搜索树按顺序遍历返回未定义作为答案的一部分
- python - 在 Pandas 中使用字符值创建新行
- c# - Access GSuite user mailboxes using admin credentials
- javascript - 如何使用 highcharts 指向数据中第二个索引的范围(dataClasses)?
- vba - Workbook_Open 下标超出范围
- c# - 如何使用 XUnit 在 ASP.NET Core 中使用依赖注入测试控制器?
- php - 当用户点击“搜索”按钮时,在表格中显示搜索结果