Crop image to match container aspect ratio
by tonytlwu
HTML
Original aspect ratio
<br /><span class='aspect'></span>
<br />
<br />Result dimensions
<br /><span class='result'></span>
<br />
<br />Result aspect ratio
<br /><span class='result-aspect'></span>
<br />
<br />
<div id="source-image"></div>
<br />
<br />
<div id="final-image"></div>
CSS
* {
font-family: monospace;
color: #999;
}
span {
font-weight: bold;
color: #333;
}
#final-image {
border: 1px solid #ccc;
}
JavaScript
/*
Crop image to match container aspect ratio
*/
function createImage(w, h) {
var img = new Image();
img.src = 'http://placehold.it/' + w + 'x' + h;
return img;
}
// Initialise parameter values
var cw = 270;
var ch = 170;
var iw = 100;
var ih = 200;
// Get container and image aspect ratio
var ca = cw / ch;
var ia = iw / ih;
var fw, fh;
// Calculate the final width and height based the aspect ratio comparison
if (ca > ia) {
fw = iw;
fh = Math.round(iw / ca);
} else {
fw = Math.round(ih * ca);
fh = ih;
}
$('.aspect').append(ca + ' : 1');
$('.result').append(fw + ' × ' + fh);
$('.result-aspect').append(fw / fh + ' : 1');
$('#source-image').html(createImage(iw, ih));
$('#final-image').css({
width: cw,
height: ch
}).html(createImage(fw, fh));