Javascript 确定矩形内图像的最大可能大小
我有一个函数,我用它来确定一个图像在一个特定矩形内可以达到的绝对最大大小(同时保持其纵横比)。我目前使用的代码肯定是错误的,但我不确定哪里出错了Javascript 确定矩形内图像的最大可能大小,javascript,algorithm,image,math,Javascript,Algorithm,Image,Math,我有一个函数,我用它来确定一个图像在一个特定矩形内可以达到的绝对最大大小(同时保持其纵横比)。我目前使用的代码肯定是错误的,但我不确定哪里出错了 // Sets the image to the largest proportional size possible // based on the current browser window dimensions and original // image size specified by the image loader function a
// Sets the image to the largest proportional size possible
// based on the current browser window dimensions and original
// image size specified by the image loader
function applyLargestProportionalSize() {
var maxWidth = <width of container>;
var maxHeight = <height of container>;
var realWidth = <actual image width>;
var realHeight = <actual image height>;
if (realWidth < realHeight && maxWidth > maxHeight) {
var scaledWidth = Math.min(realWidth, maxWidth);
$('img').css('width', scaledWidth);
// let height be determined by the browser
} else {
var scaledHeight = Math.min(realHeight, maxHeight);
$('img').css('height', scaledHeight);
// let width be determined by the browser
}
}
//将图像设置为可能的最大比例大小
//基于当前浏览器窗口尺寸和原始
//图像加载程序指定的图像大小
函数applyLargestProportionalSize(){
var maxWidth=;
var maxHeight=;
var realWidth=;
var realHeight=;
if(realWidthmaxHeight){
var scaledWidth=Math.min(realWidth,maxWidth);
$('img').css('width',scaledWidth);
//让高度由浏览器决定
}否则{
var scaledHeight=Math.min(realHeight,maxHeight);
$('img').css('height',scaledHeight);
//让宽度由浏览器决定
}
}
我不懂javascript,但问题是,您的代码只能处理容器的纵横比小于1,而图像的纵横比大于1的情况(或者可能我有这种情况,我不确定纵横比的确切定义)。试试这个:
if (realWidth/realHeight > maxWidth/maxHeight) {
// everything else the same
缩放两种情况下的图像尺寸:
scaled_width = image_width * container_height / image_height
scaled_height = container_height
scaled_height = image_height * container_width / image_width
scaled_width = container_width
如果图像比容器宽,则只有第二个适合。您如何知道代码错误?有什么问题吗?至少在这一部分,“如果图像和容器的纵横比相同,它们都会匹配。”,使用这种方法进行浮点比较不会有一些问题吗?事实上,该算法在整数运算中运行良好——出于这个原因,我特意将乘法放在第一位。但即使你用浮点运算,也没关系,因为我们不在乎它们的epsilon是否不同。事实上,两者都适合,与其说是正确操作的必要性,不如说是对算法正在做什么的评论。