ImageAreaSelect: preselect biggest thumbnail possible respecting aspectRatio

非 Y 不嫁゛ 提交于 2019-12-06 08:56:23

Try this code

        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 This code creates a centered selection area with given aspect ratio and max width. If max width exceeds that of the image, it uses image's width as max width. Please note that it works with jquery 1.8.3 which I think is because of the imageareaselect plugin not being compatible with newest jquery verions (I'm not sure though).


Update

I've improved the code to include the cases of height overflwo and aspectRatio > 1. I hope this works in all conditions :)

        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
        });

I prepared this little fiddle. It took me a little longer than Ejay, but I included a visual demonstration.

After calculating the position and width of the thumb, you could call it simple as that. (Using variable names from the fiddle)

$('#thumbnail').imgAreaSelect({ 
    x1: thumbX,
    y1: thumbY,
    x2: thumbX+thumbW,
    y2: thumbY+thumbH,
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!