gpt4 book ai didi

javascript - 无法从源读取图像的高度/宽度

转载 作者:行者123 更新时间:2023-11-28 14:32:19 25 4
gpt4 key购买 nike

我正在使用reactjs,并且我有一个用于我的iamge的组件:

这是我的代码:

import  React from "react";
require("../../../../css/story/body/story-body.css");
export class StoryImage extends React.Component{

render() {
var imgHtmlElement="";
var img = new Image();
img.src= "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";
var height = img.height;
var width = img.width;

console.log("height: "+height+"width: "+width);
imgHtmlElement=<img
src={this.props.imgUrl!=undefined?this.props.imgUrl.desktopUri:""}
className="img-responsive11" alt="" />

return (
<div>
{imgHtmlElement}
</div>);
}

}

我想做的是在将图像加载到源之前读取其源中图像的高度和宽度,然后根据其尺寸进行决定。

正如您在我的代码中看到的,我正在尝试这样做:

 var img = new Image();
img.src= "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";
console.log(img.src);
var height = img.height;
var width = img.width;

console.log("height: "+height+"width: "+width);

这就是我得到的全部:

height: 0 width: 0

我的方法有什么问题吗?有人可以帮忙吗?

最佳答案

您必须等待图像加载后才能检查其宽度高度

您可以使用 onload 属性来实现:

let img = new Image();
let height, width;
img.onload = () => {
height = img.height;
width = img.width;

console.log("height: " + height + "width: " + width);
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";

关于javascript - 无法从源读取图像的高度/宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com