Juan Bonnett
Juan Bonnett

Reputation: 1853

Canvas - Maintain a 16:9 aspect ratio relative to Height

This questions should be very easy, I haven't been able to find out! even seeing other posts about keeping aspect ratio, because they're all talking about maintaining an aspect ratio relative to width.

For example, if I want it to have a full Width canvas and keep an aspect ratio of 16:9 I would use this code:

var can = document.getElementById('canvas');
can.width = window.innerWidth;
can.height = can.width * (9 / 16);

I'm trying to make a Canvas the height of the user browser, that's the easy part.

But how can I calculate what Width the canvas should have? For example:

If I have the height 768, I know the width should be 1360, that would keep an aspect ration of 16:9, but what's the formula to calculate the width seeing that the height is variable?

Thank you before hand!

Upvotes: 0

Views: 3369

Answers (1)

David Chelliah
David Chelliah

Reputation: 1349

Based on your code, the relative width can be calculated as follows

var can = document.getElementById('canvas');
can.height = window.innerHeight;
can.width = can.height * (16/9);

Upvotes: 3

Related Questions