I have some images with random dimension and the the question is how can I scale (resize) it to exactly 960×1280 for example in JavaScript, but keep image origin aspect ratio:
I had read some on this topic but still could not resolve the problem.
This is not working for me: How to resize images proportionally / keeping the aspect ratio?
UPDATED: Working solution here, many thank to @Mr. Polywhirl Update solution
In order to figure out the aspect ratio to use for scaling, you need to figure out which dimension is larger. One you do that, you just divide the image width/height by the viewer's width/height and that should determine the scaling factor.
Centering can be achieved by finding the offset of the scaled image within the viewer.
var ctx = document.getElementById('image-viewer').getContext('2d');
var images = [
'http://i.imgur.com/5PF0Xdi.jpg',
'http://i.imgur.com/po0fJFT.png',
'http://i.imgur.com/Ijzdt0o.png'
];
var counter = 0;
// Load a new image after 2 seconds.
setInterval(function() {
loadScaleAndCenterImage(ctx, images[counter++ % images.length]);
}, 2000);
function loadScaleAndCenterImage(ctx, url) {
var imageObj = new Image();
imageObj.onload = function(e) {
var ctxWidth = ctx.canvas.width,
ctxHeight = ctx.canvas.height;
var imgWidth = imageObj.width,
imgHeight = imageObj.height;
var ratioWidth = imgWidth / ctxWidth,
ratioHeight = imgHeight / ctxHeight,
ratioAspect = ratioWidth > 1 ? ratioWidth : ratioHeight > 1 ? ratioHeight : 1;
var newWidth = imgWidth / ratioAspect,
newHeight = imgHeight / ratioAspect;
var offsetX = (ctxWidth / 2) - (newWidth / 2),
offsetY = (ctxHeight / 2) - (newHeight / 2);
ctx.clearRect(0, 0, ctxWidth, ctxHeight);
ctx.drawImage(this, offsetX, offsetY, newWidth, newHeight);
};
imageObj.src = url;
}
#image-viewer {
background-color: #E4E4E4;
background-image:
linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F),
linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F);
background-size: 20px 20px;
background-position: 0 0, 30px 30px
}
<canvas id="image-viewer" width="1280" height="960"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With