Home > Blockchain >  Resize html canvas to all available width and down to the bottom
Resize html canvas to all available width and down to the bottom

Time:10-28

I'm looking to set up an html page in which I show some text and a html canvas. The text would go above the canvas and some extra text could go to one side. Respectively, A and B in this diagram.
A solution using css only would be preferred but I have no issue in using js. It can be assumed the text will be short enough that scrolling won't be needed.


I experimented a bit with js and getting the size of the viewport (code below) but the canvas goes beyond the viewport. And that's due to existing rules for margins. I can probably make some math with margins and that kind of stuff but I want to avoid that since it would get tricker if the page progress later on into a more complicated layout.

  • problem.html:
<html>
  <head>
    <meta charset="utf-8">
    <script src="problem.js"></script>
  </head>
  <body>
    <h1>Some fancy title</h1>
    <canvas id="my-canvas"></canvas>
  </body>
</html>
  • problem.js:
window.addEventListener('DOMContentLoaded', () => {
  const ctx = document.getElementById('my-canvas').getContext('2d');

  // https://stackoverflow.com/a/28241682/2923526
  const width = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;
  const height = window.innerHeight
    || document.documentElement.clientHeight
    || document.body.clientHeight;
  ctx.canvas.width = width
  ctx.canvas.height = height

  ctx.fillStyle = "#7fdbbb"
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)
})

CodePudding user response:

                        <div style={{ display: 'grid', height: '100vh' }}  >
                         <p> upper text ..... </p>
                         <div style={{ display: 'flex' }} >
                            <p> side text of image </p>
                            <div style={{ height: '100vh' }}> html canvas codes... </div>
                         </div>
                        </div>

this piece of code can create the layout that you want.

CodePudding user response:

You can try encapsulating the canvas in a flexbox:

<div style="display:flex; flex-direction:column; height:100%;">
    <div style="display: flex; flex: 0 1 auto;">Some fancy title</div>
    <div style="display: flex; border:1px solid red; width:100%; flex: 1 1 auto;">
        <canvas id="my-canvas" width="100%" height="100%"></canvas>
    </div>
</div>
  • Related