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

标签 javascript algorithm

我有 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/

相关文章:

algorithm - 了解维特比算法

c++ - 将输入文件中的数据位置更改为.cpp程序

java - 什么设计模式适合处理很多条件分支

javascript - TypeError : image. elevateZoom is not a function : Failure in Magento 1. 9 RWD 主题

algorithm - 有没有办法评估 B+ 树所需的叶子数量?

java - 计算整数范围内数字出现次数的非递归方法

javascript - 如何在 Google Maps API 搜索结果中显示自定义地点?

javascript - Extjs TreePanel 未展开

javascript - 文本区域值更改时双击 iPad 设备

javascript - express-validator - req.checkBody 不是函数