我有3个随机图像和一个固定块(200x300px)。
请帮我写一个算法,我需要按比例改变图像大小才能进入固定块。
图像宽度必须等于块宽
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;
}
答案 0 :(得分:1)
始终更改图像宽度以填充框宽会导致宽高比问题,并会使图片失真。我建议做这样的事情。
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;
}
编辑------------------------ 如果要求具有完整的块宽度,并且图像的失真是无关紧要的,那么请改为执行此操作。
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;
}
答案 1 :(得分:0)
要将图像的宽度更改为固定的块宽度200,请将大小定义更改为:
width: 200,
height: size[1]*200/size[0]
这会在将图像调整到适当宽度时保留纵横比。
请注意,生成的图像可能会高于指定的高度。如果原始图片为100x200
,则生成的已调整大小的图片将为200x400
。鉴于问题的限制,这是不可避免的。