ImageAreaSelect:预选最大的缩略图,尊重aspectRatio

Ton*_*bet 2 javascript jquery crop jquery-plugins aspect-ratio

这是我第一次尝试的方式:

$('#thumbnail').imgAreaSelect({ 
    x1: 5,
    y1: 5,
    x2: $('#thumbnail').width(),
    y2: $('#thumbnail').width()*0.66,
    aspectRatio: '1:0.66'
});
Run Code Online (Sandbox Code Playgroud)

但是一些裁剪的图像不会溢出......

这似乎是我试过的大多数图像分辨率的预选...

var thwidth = $('#thumbnail').width();
var thheight = $('#thumbnail').height();
aspectRatio = 0.66;

$('#thumbnail').imgAreaSelect({ 
    x1: 5,
    y1: 5,
    x2: thwidth - 80,
    y2: (thwidth - 80) * aspectRatio,
    aspectRatio: '1:0.66'
});
Run Code Online (Sandbox Code Playgroud)

但它不会选择最大可能; 加上它对我来说有点脏......

如何选择与宽高比相关的最大(如果可能的话)中心宽度坐标?(在这种情况下:1:0.66)

Eja*_*jaz 5

试试这个代码

        var selWidth = 500;

        var photo = $('#photo'),
           photoWidth = parseInt($('#photo').width()),
           maxWidth = Math.min(selWidth, photoWidth)
           aspectRatio = 0.66,
           maxHeight = maxWidth * aspectRatio,
           yTop = parseInt(photo.height()) / 2 - maxHeight / 2;

        $('img#photo').imgAreaSelect({
           x1: photoWidth / 2 - maxWidth / 2,
           y1: yTop,
           x2: (photoWidth / 2 - maxWidth / 2) + maxWidth,
           y2: yTop + maxHeight
        });
Run Code Online (Sandbox Code Playgroud)

jsfiddle此代码创建一个具有给定宽高比最大宽度居中选择区域.如果最大宽度超过图像的宽度,则使用图像的宽度作为最大宽度.请注意,它适用于jquery 1.8.3,我认为这是因为imageareaselect插件与最新的jquery版本不兼容(我不确定).


更新

我改进了代码,包括高度overflwoaspectRatio> 1的情况.我希望这适用于所有条件:)

        var selWidth = 350;

        var photo = $('#photo'),
           photoWidth = parseInt($('#photo').width()),
           photoHeight = parseInt($('#photo').height()),
           maxWidth = Math.min(selWidth, photoWidth),
           aspectRatio = 0.66,
           maxHeight = maxWidth * aspectRatio;

        if (maxHeight > photoHeight) {
           maxHeight = photoHeight;
           maxWidth = maxHeight * ( 1 / aspectRatio);
        }

        var yTop = photoHeight / 2 - maxHeight / 2;

        $('img#photo').imgAreaSelect({
           x1: photoWidth / 2 - maxWidth / 2,
           y1: yTop,
           x2: (photoWidth / 2 - maxWidth / 2) + maxWidth,
           y2: yTop + maxHeight
        });
Run Code Online (Sandbox Code Playgroud)