Fix Ratio

By default, if you use relative length units Gameface will resize the UI in your game to fill the full resolution of the window. However, you can achieve a fixed aspect ratio, where the UI of your game will retain a constant width to height ratio, regardless of the size of the window in which the game is running.

If you want to set the aspect ratio of your interface to 16:9 no matter the size or ratio of the monitor or display, use em units to set the width and height of the UI container. The container needs to have 100% width so the initial font-size must be set to 11.111 (100/9).

To dynamically adjust the font-size, you must create a CSS variable:

:root {
    --font-size: 11.111vh;
 }
 .ratio-wrapper {
      background-color: #bada55;
      font-size: var(--font-size);
      width: 16em;
      height: 9em;
 }

If the screen ratio is different from 16/9, the font size must be adjusted to take 100% of the viewport width. To preserve the aspect ratio, set the font size to 6.25vw (100/16).

To calculate the screen’s aspect ratio, find the greatest common divisor of the screen’s width and height values and divide the width and height by it:

function findGCD (a, b) {
    return (b == 0) ? a : findGCD(b, a % b);
}

function keepAspectRatio () {
    const width = window.innerWidth;
    const height = window.innerHeight;
    const gcd = findGCD(width, height);
    const root = document.documentElement;

    if (9 / 16 < (height / gcd) / (width / gcd)) {
      root.style.setProperty('--font-size', '6.25vw');
    } else {
      root.style.setProperty('--font-size', '11.111vh');
    }
}

  keepAspectRatio();


  window.addEventListener('resize', keepAspectRatio);