如何更改图像以保持纵横比?
我有以下 HTML 代码:
<img id="Card00" src="images/words/back.png" onclick="imageClicked(0,0);">
和以下 Javascript 代码:
function ShowImage(id, row, column)
{
var imagePath = 'images/words/' + id + '.png';
var imgId = '#Card' + row + '' + column;
$(imgId).attr('src', imagePath);
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
if (width > height)
$(imgId).attr('width', 200);
else
$(imgId).attr('height', 200);
}
imageClicked
仅调用 ShowImage
。
Back.png
为 200x200。我想用另一张图片更改 back.png 图像。另一个 (id + .png)
大于 200x200,所以我需要在 ShowImage
函数上调整它的大小。
但我不能这样做,因为我无法在这段代码中获取它的新宽度和高度:
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
我的目标是用另一个图像更改 back.png
图像,保持宽高比无线电。
还有另一个问题:首先我看到更大的图像,然后有时它会变成 200x200。我说有时是因为有时我会得到它的宽度或高度。
有什么建议吗?
I have the following HTML code:
<img id="Card00" src="images/words/back.png" onclick="imageClicked(0,0);">
And the following Javascript code:
function ShowImage(id, row, column)
{
var imagePath = 'images/words/' + id + '.png';
var imgId = '#Card' + row + '' + column;
$(imgId).attr('src', imagePath);
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
if (width > height)
$(imgId).attr('width', 200);
else
$(imgId).attr('height', 200);
}
imageClicked
only calls ShowImage
.
Back.png
is 200x200. I want to change back.png image with another one. That another one (id + .png)
, is bigger than 200x200, so I need to resize it on ShowImage
function.
But I can't do that, because I can't get its new width and height in this piece of code:
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
My goal is to change back.png
image with another one, keeping aspect radio.
And there is another problem: first I see the bigger image, and then, sometimes, it gets 200x200. I said sometimes because sometimes I get its width or its height.
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的办法是首先将图像加载到内存中,然后在加载后获取其真实的高度和宽度,使用该信息(URL、高度和宽度)来确定适当的尺寸。但请注意,这并不是万无一失的,因为缓存可能会搞砸。
请注意,您可以概括以下内容以在函数本身中包含最大尺寸,但我认为它很容易适应:
jsFiddle 示例
编辑
根据下面的评论交换了
attr
和load
的位置。除此之外,我不会对优化过于疯狂,因为如果我们想要完美的东西,我们真正要做的就是预加载所有内容,获取其真实尺寸,并在每次更改原始图像时使用该信息。The best thing to do is just load the image into memory first, then once it loads get its real height and width, use that info -- URL, height and width -- to determine the appropriate dimensions. Note that this isn't foolproof, though, as caching can mess it up.
Note that you can generalize the below to include maximum dimensions in the function itself, but I think it's pretty easily adaptable:
jsFiddle Example
EDIT
Swapped places of
attr
andload
per the comment below. I'm not going to go too crazy with optimization beyond that, as what we'd really do if we wanted things perfect would be to preload everything, get its real dimensions, and use that information each time we change the original image.你尝试过吗:
Did you try: