0
\$\begingroup\$

Before I start my question, let me clarify that I'm not using <canvas>, I'm using <div id="canvas">, so I'm not using HTML5 Canvas for this game.

I have this div element named canvas that has an aspect ratio of 16 / 9, and I'm trying to place elements inside, but the issue is that the elements inside the canvas either don't change their size, or they get stretched awkwardly. I want to get the elements to fit inside the canvas without warping their size and without moving them out of place. How is this achievable? I'm ok with answers that has a little bit of JavaScript involved.

Here is my window when it is wider than the canvas (this is what I prefer): A red box in a white element named canvas, on a black body seen on the left and right

And here it is when the canvas is wider than the window (this is the issue):

Same as above, but on a smaller window where the body is seen on the top and bottom

// If you go into full screen on this snippet, resize your browser window (Or rotate your device if you are using a phone) and see how the box acts weirdly.
body{ font-family: 'SF Intermosaic', sans-serif; margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; min-height: 100vh; } #canvas{ width: 100%; max-width: calc(100vh * (16 / 9)); aspect-ratio: 16 / 9; background: rgb(255, 255, 255); position: relative; } #opening{ background: darkblue; } .child-element { width: 10ch; /* Change the units to width, height, top, and left values to em, %, vw, and vh to see my issue*/ height: 10ch; background: red; position: absolute; top: 10ch; left: 10ch; } If you go into full screen on this snippet, resize your browser window (Or rotate your device if you are using a phone) and see how the box acts weirdly.
<!DOCTYPE html> <html lang="en"> <head> <title>Game</title> </head> <body> <div id="canvas"> <div class="child-element"></div> </div> </body> </html>

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

With a little help, I figured it out. If I go with %, instead of using height to make the red box taller, I need to use padding-bottom.

Here is an example:

body{ font-family: 'SF Intermosaic', sans-serif; margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; min-height: 100vh; } #canvas{ width: 100%; max-width: calc(100vh * (16 / 9)); aspect-ratio: 16 / 9; background: rgb(255, 255, 255); position: relative; } #opening{ background: darkblue; } .child-element { width: 10%; height: 0; background: red; position: absolute; top: 10%; left: 10%; padding-bottom: 10%; }
<!DOCTYPE html> <html lang="en"> <head> <title>Game</title> </head> <body> <div id="canvas"> <div class="child-element"></div> </div> </body> </html>

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.