I am facing a challenge with a canvas element placed inside a flexbox that can be resized. My goal is to have the canvas fill the available space while maintaining its aspect ratio (2/3) and without getting cut off.
(I prefer adjusting the CSS dimensions rather than the canvas resolution).
I've experimented with object-fit: contain
and clamp(...)
, but haven't achieved the desired outcome. The canvas either loses its aspect ratio or extends beyond its container.
body{
margin:0;
}
#mainContent {
background:grey;
height:100vh;
display:flex;
flex-wrap:nowrap;
align-items:center;
}
#someOtherElem {
background:red;
width:200px;
height:200px;
margin-left:1rem;
}
#canvasContainer {
display:flex;
flex:1;
height:100%;
justify-content:center;
align-items:center;
}
canvas {
width:calc(100%-2rem);
height:calc(100%-2rem);
background:green;
object-fit:contain;
}
<div id="mainContent">
<div id="someOtherElem"></div>
<div id="canvasContainer">
<canvas height="300" width="200"></canvas>
</div>
</div>
Here's a simplified version of my attempts: https://jsfiddle.net/mwq4502v/.
I'm unsure about the best approach to achieve this, so any guidance would be highly appreciated!