gpt4 book ai didi

javascript - 在固定 block 中按比例调整图像大小

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:26:30 27 4
gpt4 key购买 nike

我有 3 张随机图片和一张固定 block (200x300px)。

请帮我写一个算法,我需要按比例改变图像大小才能进入固定 block 。

图片宽度必须等于 block 宽度

http://jsfiddle.net/U8AAu/2/

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com