使用 Javascript 调整图像大小以使其适合视口

Resize images with Javascript to fit them within the viewport

我正在调用一个 API 那个 returns 一个 URL 到一个图像,图像可以是任何大小并且它是完全随机的。

我正在尝试调整图像大小以适合页面,确保内容不会被推到首屏以下,或者图像不会达到页面宽度。

我在下面写了一些 Javascript,我一直在测试它并得到一些奇怪的结果 - 控制台日志说图像是一种尺寸,但 [=21] 中的元素选择器=] 的开发工具通常说的是完全不同的东西。我确定我的代码中犯了一些基本错误,如果你能看一下那就太好了。

Javascript 设置视口高度和宽度,检查照片源是否可用。加载图像后,它会检查自然尺寸是否大于视口的尺寸,如果是,它会尝试调整大小 - 这是脚本失败的地方。

            //check viewport
            var viewportWidth = getWidth();
            var viewportHeight = getHeight();

            //get the media
            if (data[2] == "photo") {
                var tweetImage = document.getElementById("tweetImage");
                //when it loads check the size against the browser size
                tweetImage.onload = function () {
                    console.log('image height: ' + tweetImage.naturalHeight);
                    console.log('viewport height: ' + viewportHeight);

                    //does it matter if its landscape?
                    if (viewportWidth - tweetImage.naturalWidth < 1) {
                        tweetImage.width = Math.floor(tweetImage.naturalWidth - (viewportWidth - tweetImage.naturalWidth) * 1.2);
                        console.log('w');
                    } else if (Math.floor(viewportHeight - tweetImage.naturalHeight) < 1) {
                        console.log('h');
                        console.log(viewportHeight - tweetImage.naturalHeight);
                        console.log('changed result: ' + Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight))));
                        tweetImage.height = Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight)*1.2));

                    } else {
                        tweetImage.height = Math.floor(viewportHeight / 2);

                    }
                    tweetImage.align = "center";
                    tweetImage.paddingBottom = "10px";

                };
                //tweetImage.height = Math.floor(viewportHeight / 2);
                tweetImage.src = data[3];

            }

一种选择是使用基于 CSS 的解决方案,例如视口高度单位。

.example {
    height: 50vh; // 50% of viewport height
}

http://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/