试试这个代码
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
});
jsfiddle此代码创建具有给定纵横比和最大宽度的居中选择区域。如果最大宽度超过图像的宽度,则使用图像的宽度作为最大宽度。请注意,它适用于 jquery 1.8.3,我认为这是因为 imageareaselect 插件与最新的 jquery 版本不兼容(不过我不确定)。
更新
我改进了代码以包含height overflwo和aspectRatio > 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
});