将 html canvas 调整到所有可用宽度并向下调整到底部

Resize html canvas to all available width and down to the bottom

我想建立一个 html 页面,在其中显示一些文本和一个 html canvas。文本将位于 canvas 之上,并且一些额外的文本可以位于一侧。分别是this diagram.
中的A和B 仅使用 css 的解决方案是首选,但我在使用 js 方面没有问题。可以假设文本足够短,不需要滚动。


我对 js 进行了一些试验并获取了视口的大小(下面的代码),但是 canvas 超出了视口。这是由于现有的利润率规则。我可能可以用边距和类似的东西做一些数学运算,但我想避免这种情况,因为如果页面稍后进入更复杂的布局,它会变得更复杂。

<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>
window.addEventListener('DOMContentLoaded', () => {
  const ctx = document.getElementById('my-canvas').getContext('2d');

  // 
  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)
})
                        <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>

这段代码可以创建你想要的布局。

您可以尝试将 canvas 封装在 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>