I have the following Codepen:
window.addEventListener('resize', function updateBox() {
const maxWidth = window.innerWidth * 0.8
const maxHeight = window.innerHeight * 0.8
const width = 1024
const height = 600
const ratio = Math.min(maxWidth / width, maxHeight / height)
const box = document.getElementById("box")
console.log(`resize: ${width*ratio}*${height*ratio}`)
box.style = `width: ${width * ratio}px;`
box.style = `height: ${height * ratio}px;`
});
#box {
width: 1024px;
height: 600px;
background-color: red;
}
<div id="box"></div>
This is pulled out of a popular question How to resize images proportionally / keeping the aspect ratio?. It is a very popular answer but it doesn't give the perfect aspect ratio.
As you can see if you resize the browser window, it looks weird. It does not maintain aspect ratio. It's some random calculation making the rectangle jump up in width & height.
I want an effect like https://codepen.io/chriscoyier/pen/BZNoev. Try resizing the browser to see the effect in action. The rectangle maintains its aspect ratio & stays in the center.
I can't use it unfortunately as it uses CSS padding-top
so I can't use it. I need to use JS to achieve this as I will be using a Canvas library named Konva.
How do I do it?