简体   繁体   中英

Resizing window to maintain aspect ratio

I have an interesting problem for a little program I have been developing.

Basically what I wish to create is a window which I can resize but still maintain a 16:9 aspect ratio (note this is for a native application using NWJS). I am also using the easelJS libraries to manipulate the canvas.

The program below basically resizes the canvas to be the same size as the window and does it's job perfectly. But I've been stuck trying to figure out exactly how to maintain the aspect ratio of the window itself.

var stage, w, h;

window.addEventListener('resize', resizeCanvas);
function resizeCanvas() {
    w = window.innerWidth;
    h = window.innerHeight;
    stage.canvas.width = w;
    stage.canvas.height = h;

Exactly what sort of calculations do I need to do to force this setting? I'm not as knowledgeable when it comes to things such as aspect ratios.

You should base your calculation on one axis only, and get the new height and width from it.
For a 16/9 ratio

 w = window.innerWidth;
 h = 9*window.innerWidth/16;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM