在渲染之前计算屏幕尺寸上的图像尺寸

时间:2017-04-12 14:20:46

标签: javascript jquery html

在渲染图像之前,有没有办法根据屏幕分辨率计算/估算图像尺寸?我需要更多的逻辑帮助而不是代码才能说实话。我需要计算什么?

图片尺寸:800px * 450px

窗口大小:424px * 728px

图像效果为424px * 239px。我需要在代码中计算这个,这样我就可以调整其后的其他元素的位置(绝对/固定元素)。

到目前为止,我所做的是;

var ratio1 = (this.retrievedNewsArticle.featuredImage.width / this.retrievedNewsArticle.featuredImage.height);
var ratio2 = ($(window).innerWidth() / this.retrievedNewsArticle.featuredImage.width);

// Ratio 1 = 424
// Ratio 2 = 0.53

那么下一步是什么?

1 个答案:

答案 0 :(得分:2)

听起来您已经知道图像的大小,听起来您希望图像是窗口的整个宽度,只需要知道如何确定图像的高度。如果是这样,目标高度是图像高度乘以窗口宽度除以图像宽度:

var renderedWidth = imageWidth;
var renderedHeight = imageHeight * (windowWidth / imageWidth);

保持宽高比。

假设图像总是比屏幕宽。让我们删除这个假设。

如果您希望图像拉伸以填充:

var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
    renderedWidth = imageWidth * (windowWidth / imageWidth);
} else {
    renderedWidth = imageWidth;
}
renderedHeight = imageHeight * (windowWidth / renderedWidth);

如果您不希望图像伸展以填充:

var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
    renderedWidth = imageWidth;
    renderedHeight = imageHeight;
} else {
    renderedWidth = imageWidth;
    renderedHeight = imageHeight * (windowWidth / imageWidth);
}
相关问题