Canvas in flexbox not resizing properly
Any idea why the canvas in this example code takes the full width of the viewport?
https://codepen.io/codecab/pen/abXaKJr?editors=1100
When I replace the
canvas
with a div
it works as expected. I put the canvas in a wrapper element for now, which works, but I'd like to understand why its behaving as it does. Am I missing something?29 Replies
your body has a height of 100vh and has display: flex;
the canvas has flex-grow: 1 which allows it to grow to the full available space of the flex container (the body)
but why does it behave differently when i replace the canvas with a div ?
because your div probably is not a flex-container
try it out for yourself in the pen, just change canvas to div
flex-grow works only when its parent has display flex
so if you put a div in between, it has no effect, and it wont grow
not in between
i mean around
instead of
with same css, behaves differently, thats what is confusing to me
ah okay, now i see what you mean.
thank you 😄
haha, that indeed is strange. never noticed that with canvas. really weird. have to dive into that
somehow it grows respecting the aspect-ratio and gets to wide
yeah that what i was thinking too, but
object-fit: none
didn't have any effect eitherhave never seen that behaviour before.
even with unset: all as the first line in canvas, it still does it
first time in years i have to actually wrap an element for it to behave
i always had canvas within a wrapper, so never noticed this
i guess its an acceptable workaround, but im still curious so if you happen to have an idea, lmk 🙂
when you set width: 0 it works
there must be a logical reason why it behaves like this (which I can not think of).
huh, indeed
min-width: 0
works as welli do think you would like to respect the dimensions. what you draw on to it wont be responsive. the ctx needs to know the size
it will stretch what you draw
i'm playing around with creating a minigame, so as part of my render loop i resize the canvas like this
ah ok.. yea, might work for you
for now it does. first time really diving into
canvas
so i'll probably make a lot of mistakes along the way, but that's the fun part, isnt it
anyways, i removed the wrapper and added min-width
, thanks for helping out 🙂if you want to do it all in vanilla js. i'd recommend watching franks labarotory on youtube. he makes great things on canvas ans explains it really well
i faintly remember something about some elements in some circumstances needing an explicit width set, but for the love of god i can't remember any specifics
alright, might check it out 🙂
was a long time ago i did something on canvas. i made some easy clocks and small tic tac toe like games, but that's about it.
here some older pens https://codepen.io/collection/waQVVW
nice, the bubbly beer is a neat effect
did you use a tool to generate the transforms applied here?
ah nvm its svg code