I'm working on a game project using HTML canvas and javascript. The canvas I am using has dimensions of 1280 x 720 px with a 16:9 aspect ratio. My goal is to have the game displayed at fullscreen, but with black bars shown if the screen ratio is not 16:9.
Here are the challenges I encountered:
canvas {
position: absolute;
width: 100%;
height: 100%;
}
With this code, my game fills the entire screen but gets stretched if the screen's ratio is different from 16:9. I prefer not to have it stretched; rather, I would like to display black bars if necessary.
Another attempt I made was:
canvas {
position: relative;
width: 100%;
height: 100%;
}
Although this preserves the correct aspect ratio, it results in parts of the canvas being cut off when the screen is wider than 16:9, which is not ideal for the game experience.
So, how can I solve this dilemma? Some suggestions involve dynamically updating canvas.width and canvas.height on window resize events, but I would prefer not to alter these dimensions since the game mechanics are based on a 1280 x 720 resolution. While scaling the drawings according to canvas.width and canvas.height could work, I am curious if there is another solution that avoids this method.
Your insights and suggestions are greatly appreciated. Thank you!