Search code examples
javascriptreactjsstyled-components

ReactJS: Resizing a canvas inside a flexbox


I'm struggling with trying to get a canvas to be dynamically resized to fill the bottom part of a web page when the browser resizes. The canvas will be resized correctly when increasing the browser window size, but will remain the same size when decreasing the browser window size.

How can I get the canvas to shrink in size along with the browser window?

Here's where I'm at now: https://codesandbox.io/s/thirsty-pare-vk4yb


Solution

  • It's happening because you set the canvas's height on resize so it can be bigger, but once the canvas' height has been set, its parent can't be shorter.

    You can get rid of sets the canvas' height (I'm following your example, I'm not sure how it will affect on the real case) and use a similar approach as <Container /> and <FloorPlanWrapper /> - set the parent display: flex and the child flex-grow: 1.

    Like this:

    const FloorPlanWrapper = styled.div`
      flex-grow: 1;
      background-color: blue;
      display: flex;
      flex-direction: column;
    `;
    
    const StyledCanvas = styled.canvas`
      background-color: yellow;
      display: block;
      flex-grow: 1;
    `;
    

    https://codesandbox.io/s/boring-dubinsky-0rzyi

    Notice: Even though flexbox can take care of the canvas size it can't take care about the its resolution. In order to do so, you need to listen to window resize and update its resolution (canvas.width = canvas.height * (canvas.clientWidth / canvas.clientHeight);) and then re-render it.

    https://codesandbox.io/s/boring-dubinsky-0rzyi

    Thanks to https://bob1german.com/2015/03/09/stretching-the-html-5-canvas-fixing-aspect-ratio-problems/ for this formula