如何使用 JavaScript 将图像缩放到全屏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8158012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:29:12  来源:igfitidea点击:

How to scale an image to full screen using JavaScript?

javascriptimageimage-resizing

提问by Andrew

I have an image that I would like to scale to full screen. How would I do this using JavaScript/jQuery? No animation is necessary, just resizing the image.

我有一个图像,我想缩放到全屏。我将如何使用 JavaScript/jQuery 做到这一点?不需要动画,只需调整图像大小。

<img src="something.jpg" onload="scaleToFullScreen()" />

回答by Andrew

The only reliable solution is to use a formula to determine maximum scale ratio:

唯一可靠的解决方案是使用公式来确定最大缩放比例

var $img = $('#content img'),
    imageWidth = $img[0].width, //need the raw width due to a jquery bug that affects chrome
    imageHeight = $img[0].height, //need the raw height due to a jquery bug that affects chrome
    maxWidth = $(window).width(),
    maxHeight = $(window).height(),
    widthRatio = maxWidth / imageWidth,
    heightRatio = maxHeight / imageHeight;

var ratio = widthRatio; //default to the width ratio until proven wrong

if (widthRatio * imageHeight > maxHeight) {
    ratio = heightRatio;
}

//now resize the image relative to the ratio
$img.attr('width', imageWidth * ratio)
    .attr('height', imageHeight * ratio);

//and center the image vertically and horizontally
$img.css({
    margin: 'auto',
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0
});

回答by locrizak

If you have it outside of all elements you can just use css: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />

如果你在所有元素之外都有它,你可以使用 css: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />

if you do not:

如果你不:

<img name='myImage' src="something.jpg" onload="onResize()" />
<script>
window.onresize = onResize;

function onResize(e){
    var img = var img = document.images.myImage;
    if ( img.width > img.height )
        img.width = window.innerWidth
    else
        img.height = window.innerHeight;
}
</script>

回答by Khaled AbuShqear

You can use viewerjswhich is perfict library to able users to browse your images to view fullpage and fullscreen, slide them and view slide between them check this link : https://github.com/fengyuanchen/viewerjs

您可以使用viewerjs完美的库让用户浏览您的图像以查看全屏和全屏,滑动它们并查看它们之间的幻灯片检查此链接:https: //github.com/fengyuanchen/viewerjs