I am trying to make a canvas element fit to its container div using Javascript rather than CSS, because this way it doesn't stretch anything drawn inside the canvas.
Currently, if I refresh the page, sometimes the canvas element fits perfectly inside. Other times, when I refresh, its width is greater than the container, and its height is lesser than the container. I have no idea why I get this different behavior upon refreshing the page, even without resizing the window.
Here's how I set up the canvas size:
const ctxX = canvasParent.offsetWidth - 4;
const ctxY = canvasParent.offsetHeight - 4;
canvasEl.width = ctxX;
canvasEl.height = ctxY;
const ctx = canvasEl.getContext("2d");
I read that setting size like this only works if the container is positioned relative, so this is the CSS for the container:
display: block;
position: relative;
height: 60%;
margin-top: 2%;
border: 2px solid v.$border;