Search code examples
javascriptjqueryjquery-pluginscropaspect-ratio

ImageAreaSelect: preselect biggest thumbnail possible respecting aspectRatio


This is how I first tried:

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

But some of the cropped image stay off the overflow...

This seems to make a preselection for most of the image resolutions I tried...

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

But it won't select the maximum possible; plus it looks a bit dirty to me...

How can I select the biggest (centereded, if possible) width/height coordinates that respects the aspect ratio? (in this case: 1:0.66)


Solution

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