我有 3 张随机图片和一张固定 block (200x300px)。
请帮我写一个算法,我需要按比例改变图像大小才能进入固定 block 。
图片宽度必须等于 block 宽度
var images = [
getRandSizes(),
getRandSizes(),
getRandSizes()
];
var sizes = getProportionalSizes(200, 300, images);
$.each(sizes, function(i, size){
var $img = $("<div>", {
class: 'img',
width: size[0],
height: size[1]
}).appendTo('.fixed-block')
});
// todo:
function getProportionalSizes(maxWidth, maxHeight, sizes){
return sizes;
}
function getRandSizes(){
return [getRand(100,200), getRand(100,200)]
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
最佳答案
总是更改图像宽度以填充框宽度会导致宽高比问题,并且会使您的图片失真。我建议做这样的事情。
var image1 = new Object( );
var sizeArray = getRandSizes( );
image1.width = sizeArray[0];
image1.height = sizeArray[1]; //Repeat for images 2 and 3
var images =
[
image1,
image2,
image3
];
images = getProportionalSizes( 200, 300, images );
images.forEach( function( image )
{
var $img = $("<div>",
{
class: 'img',
width: image.width,
height: image.height
}).appendTo('.fixed-block')
});
function getProportionalSizes(maxWidth, maxHeight, images)
{
var totalHeight;
images.forEach( function( image )
{
totalHeight += image.height;
});
images.forEach( function( image )
{
var ratio = image.height / totalHeight;
image.height *= ratio;
image.width *= ratio; //This will ensure that images maintain aspect ratio, but that the total height of the 3 images matches the container height.
});
return images;
}
function getRandSizes()
{
return [getRand(100,200), getRand(100,200)]
}
function getRand(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
编辑------------------------ 如果要求具有完整的 block 宽度,并且图像失真无关紧要,则改为执行此操作。
function getProportionalSizes(maxWidth, maxHeight, images)
{
var totalHeight;
images.forEach( function( image )
{
totalHeight += image.height;
});
images.forEach( function( image )
{
var ratio = image.height / totalHeight;
image.height *= ratio;
image.width = maxWidth //This will keep the individual image height proportional to each other, but stretch the picture in the x-direction to fill the block.
});
return images;
}
关于javascript - 在固定 block 中按比例调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24766155/