I have a question for a html5 game using canvas in javascript.
I would like that the canvas showed to the player contains either 1920 of canvas.width, either 1080 of canvas.height in order to not see the padding. That means that I don't want to keep the (optimal) game ratio 16/9 if the player resize his screen with an other ratio, but I want to keep the viewport ratio 16/9 to avoid stretching (using canvas.style.***)
Let me take an example of a player with a resizable screen (window.innerWidth = 500 and window.innerHeight = 1600), as 1600/500 > 1920 / 1080, I would like that the player can see 1920 of the game width and "less than 1080" of the game height, preventing viewport stretching.
Agar.io is an other good example.
Thank you very much !
To fit but will leave empty areas on the sides or top bottom if aspects do not match.
or to fill but will clip canvas if aspects do not match
for display 1600 by 500 and canvas 1920 by 1080
thus to fit canvas will be
0.463 * (1920,1080) = (889,500)
empty on sidesand to fill canvas will be
0.8333 * (1920,1080) = (1600,900)
clipped top and bottom.More info on scale and fit can be found below.
If you are scaling to fill the canvas you will need to account for the clipped area and find the offset to the top left corner of the canvas (this will be off the page).
Your canvas will fill the page innerWidth and innerHeight but you will need to offset all rendering. This can be done by setting the transform to the correct offsets
The canvas display size will be
and the canvas resolution will be
Below is an example of the code in action. Very lazy coding, just to show it working should really not create and destroy canvas on resizes. Also as fiddle because it has resizable panels to test with.
Scaling to fit
Means that the whole image will be visible but there may be some empty space on the sides or top and bottom if the image is not the same aspect as the canvas. The example shows the image scaled to fit. The blue on the sides is due to the fact that the image is not the same aspect as the canvas.
Scaling to fill
Means that the image is scaled so that all the canvas pixels will be covered by the image. If the image aspect is not the same as the canvas then some parts of the image will be clipped. The example shows the image scaled to fill. Note how the top and bottom of the image are no longer visible.
Example Scale to fit
Example Scale to fill
The only differance between the two functions is getting the scale. The fit uses the min fitting scale will the fill uses the max fitting scale.