大家晚上好!!
我在调整图像大小和 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),显然,它没有居中!
我真的不明白为什么会这样!!
有什么帮助吗?
谢谢大家