【问题标题】:Resize html canvas to all available width and down to the bottom将 html 画布大小调整为所有可用宽度并向下调整到底部
【发布时间】:2021-12-13 06:58:18
【问题描述】:

我希望设置一个 html 页面,在其中显示一些文本和一个 html 画布。文本会出现在画布上方,一些额外的文本可能会出现在一侧。分别是this diagram中的A和B。
仅使用 css 的解决方案将是首选,但我在使用 js 时没有问题。可以假设文本足够短以至于不需要滚动。


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

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

【问题讨论】:

    标签: javascript html css html5-canvas


    【解决方案1】:

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

    【讨论】:

    • 嘿@Vinicius,这几乎可行。画布保留在视口内。然而,出于某种原因,画布在该容器内保持为正方形,而不是占据所有水平空间。可以通过在 Web 控制台中运行 const ctx = document.getElementById('my-canvas').getContext('2d'); ctx.fillStyle = "red"; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); 来检查
    • 嘿@ffigari,您可能需要从外部 DIV 读取 bounding rectanglevar element = document.getElementById('divcanvas'); var positionInfo = element.getBoundingClientRect(); var hx = positionInfo.height; var wx = positionInfo.width; ctx.canvas.width = wx; ctx.canvas.height = hx
    【解决方案2】:
                            <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>
    

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

    【讨论】:

    • 这样,画布保持默认创建大小,其容器不会占用所有可用宽度
    • 给出与画布相关的 div 的 100% 宽度...&lt;div style={{ height: '100vh', width: '100%' }}&gt; html canvas codes... &lt;/div&gt;...如果问题解决了,请给我更新。
    猜你喜欢
    • 2017-08-11
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多