Search code examples
resizewindownode-webkitaspect-ratio

Constrain window aspect ratio in NW.JS


Is it possible to constrain the aspect ratio of a window in an NW.JS app?

I have content which is 800 x 600. In the package.json manifest, I can define the window settings as...

"window": {
  "toolbar": false
, "width": 800
, "height": 600
, "min_width": 800
, "min_height": 600
}

I use CSS to preserve the aspect ratio of the content and to fill the window as well as possible:

html, body{
  margin: 0;
  height: 100%;
}

main {
  position: relative;

  width:100vw;
  max-width:133.3333vh; /* max-width / width = aspect ratio */
  min-width: 800px;

  height:75vw;
  max-height:100vh; /* max-height / height = aspect ratio */
  min-height: 600px;

  margin: 0 auto;
}

However, if you make the window too wide, a blank area appears on either side. If you make it too tall for its width, a blank area appears at the bottom.

Is there a setting that forces a given aspect ratio?

Or is there now a window resize event that I can listen for so that I can apply window.resizeTo(height*1.333,height) as soon as the window's size is changed?


Solution

  • There does appear to be a resize event:

    You could use code like this to set your event listener:

    gui = require('nw.gui');
    w = gui.Window.get();
    w.on('resize', yourFunctionHere);
    

    but be careful about changing the window size in the handler (e.g. using resizeTo()) as that will trigger a resize and could cause all kinds of chaos. It might work to make the resize conditional on the current aspect ratio, but I can imagine you could still run into problems if you hit some limit or other. Offhand I don't know if there are some facilities (akin to event bubbling &c) that would help in this situation.