0

I'm trying to create a 16:9 canvas which remains 16:9 regardless of screen size. It works! But only in one direction...

function ratio () {
    var w = window.innerWidth;
    var newH = w * 0.5625;

    document.getElementById('design').style.height = (newH + 'px');
}

window.onload = ratio;
window.onresize = ratio;

So it works when the window's height is too large, but not when the width is too large. My tiny brain can't fathom how to make it work the other way round - when the window is too wide.

I'm aware there's a CSS workaround with padding, but that doesn't work in my case - and I'd prefer to use JS anyway.

FYI.. here's the page: https://clever-carbon.webflow.io/

Ben Wilde
  • 3
  • 2

1 Answers1

0

If I understood you correctly, this might help:

function ratio () {
    var w = window.innerWidth
    var h = window.innerHeight
    var actualRatioW = w/h
    var actualRatioH = h/w
    var desiredRatioW = 16/9
    var desiredRatioH = 9/16
    var maxW = Math.min(window.innerWidth, (desiredRatioW/actualRatioW)*window.innerWidth)
    var maxH = Math.min(window.innerHeight, (desiredRatioH/actualRatioH)*window.innerHeight)

    document.getElementById('design').style.height = (maxH + 'px');
    document.getElementById('design').style.width = (maxW + 'px');
}

window.onload = ratio;
window.onresize = ratio;

We're getting the ratio between the desired ratio and the actual ratio, applying it to the height/width, and getting the minimum value between that and the actual height/width. This helps enforce the ratio when either of the sides is too long/narrow.

You might also want to keep the height of the wrapper at 100vh

cuzox
  • 794
  • 7
  • 15