图像自适应调整大小+Javascript的问题

Problems with image adaptive resizing + Javascript

本文关键字:+Javascript 问题 自适应 调整 图像      更新时间:2023-09-26

大家晚上好!!

我正面临着一些图像调整大小的问题;Javascript。

我写了一个函数来调整图像的大小,保持纵横比。功能如下:

function computeRatio () {
        var el_image = document.getElementById("div_image");
        var newImg = new Image();           
        newImg.src = document.getElementById("image").src;
// GET IMAGE REAL DIMENSIONS
        var image_height = newImg.height;
        var image_width = newImg.width;
// SET WINDOW DIMENSIONS
        var window_height = 762;
        var window_width  = 600;
// COMPUTE DIMENSION RATIOS
        var height_ratio  = image_height / window_height;
        var width_ratio   = image_width / window_width;
// RESET IMAGE POSITION
        el_image.style.left = "0px";
        el_image.style.top = "0px";
        if (height_ratio > width_ratio) {
            var width = window_height/(image_height/image_width);
// SET NEW DIMENSIONS (MAX HEIGHT & NEW WIDTH)
            el_image.style.width  = width+"px";
            el_image.style.height = window_height+"px"
// SET NEW POSITION TO CENTER IMAGE
            var scroll_x = (window_width-width)/2;
            el_image.style.left = scroll_x+"px";
        } else {
            var height = window_width*(image_height/image_width);

// SET NEW DIMENSIONS (MAX WIDTH & NEW HEIGHT)
            el_image.style.width  = window_width+"px"
            el_image.style.height = height+"px";
            var scroll_y = (window_height-height)/2;
            el_image.style.top = scroll_y+"px";
        }
}

这是HTML:中的相关部分

<div id="div_image" style="display: block;">
    <img src="" alt="0" id="image" onLoad="computeRatio ()"/>
</div>

除了处理不太小的图像(即大小>1MB)外,它的工作非常好。

当这种情况发生时,函数会计算正确的尺寸,但随后图像会以全屏显示(W=600px,H=762px),显然,它没有居中!

我真的不明白为什么会发生这种事!!

有什么帮助吗?

感谢所有

要保持容器中图像的纵横比,只需将图像设置为display:block并添加width:100%即可。效果是图像将填充到包含元素的宽度,并且高度将自动调整。

#image {
    display:block;
    width:100%;
}