Search code examples
javascripthtmlcsscss-gridobject-fit

Scale down <canvas> within grid container so, that <canvas> retains its aspect ratio


I have a problem scaling down canvas elements that belong to grid container.

html * {
 font-size: 1em;
 font-family: Arial;
}

#wrapper {
 border: 1px solid green;
 display: grid;
 grid-template-columns: repeat(auto-fit, 32vmin);
 grid-auto-rows: minmax(32vmin, 43vmin);
 grid-column-gap: 0.4em;
 grid-row-gap: 0.4em;
 align-items: center;
 justify-items: center;
}

#wrapper > * {
 object-fit: contain;
 max-height: 32vmin;
 max-width: 32vmin;
 border: 1px solid black;
}

#canvas0 {
 width:20vmin;
 height:60vmin;
}
<html>
<body>
 <div id="wrapper">
  <canvas id="canvas0"></canvas>
 </div>
</body>
</html>

The above code shows canvas that have width: 20 and height: 60 scaled with the result aspect ratio of 1:2. What I need is a canvas element that fits into maximum grid row height and column width, and, remains constant with its aspect ratio.


Solution

  • I came up with a solution that uses Javascript. As I see it now, canvas elements must have their own width and height attributes that differ from CSS attributes. Canvas width and height is the dimensions used for drawing on the canvas. CSS width and height represent elements layout.

    CSS plus HTML layout stays basically the same from original question. Few changes here and there, but the same in general. Following that, I am setting width and height to every canvas element in Javascript, taking dimensions and aspect ratio from server. Then I scale canvas elements according to aspect ratio.

    This SO answer, and the question, have helped me to solve scaling problem.

    How do I scale one rectangle to the maximum size possible within another rectangle?