'Automatic letterbox scaling HTML5 Canvas
In Construct 2 engine there is an automatic letterbox scaling for the game canvas. I've tried to do this in my Javascript game, but i couldn't get the same result. The canvas fits vertically, but sometimes the width is high enough to overflow the screen. How can i make the canvas to fit the screen without overflowing while keeping aspect ratio like in Construct 2?
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
background-color: black
}
</style>
<script src="main.js"></script>
<meta charset="UTF-8">
<title>My Game</title>
</head>
<body id="body">
<canvas id="canvas"></canvas>
</body>
</html>
Solution 1:[1]
I would try to set the <canvas> element max-width: 100% or max-width: 100vw.
Solution 2:[2]
After trying so hard, i've finally got an answer for my question. I created a flex container with align-items as stretch (so the canvas inside it can be automatically resized), and the width and height of this container is handled by javascript, so when a resize event is triggered, the container is automatically resized to fit in screen keeping aspect ratio.
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
background-color: black;
}
#container {
display: flex;
justify-content: center;
align-items: stretch;
}
</style>
<script src="main.js"></script>
<meta charset="UTF-8">
<title>Game</title>
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
window.onload = function() {
var container = document.getElementById("container")
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
canvas.width = 640
canvas.height = 1200
}
window.addEventListener("resize", function() {
let width_scale = window.innerWidth / canvas.width
let height_scale = window.innerHeight / canvas.height
let scale = Math.min(width_scale, height_scale)
container.style.width = `${canvas.width * scale}px`
container.style.height = `${canvas.height * scale}px`
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Lévai |
| Solution 2 | Kélio Minervino |
