【问题标题】:Can't get canvas element height to equal container height无法使画布元素高度等于容器高度
【发布时间】:2015-01-24 04:40:59
【问题描述】:

我正在尝试将一系列画布元素设置为与其容器相同的高度:

$(document).ready(function() {
  var c = $('.canvas canvas');
  var container = $(c).parent();

  $(window).resize(respondCanvas);

  function respondCanvas() {
    c.each(function(index) {
      $(this).attr('width', $(container[index]).width());
      $(this).attr('height', $(container[index]).height());
    });
  }

  respondCanvas();
});
.flex {
  display: flex;
  overflow: auto;
}
#viewport {
  flex: 1 0 100%;
  flex-flow: row wrap;
  justify-content: space-between;
}
.canvas {
  display: flex; /* new addition from answer */
  background: #ccc;
  margin: 0.25rem;
}
#half-breadth,
#profile {
  flex: 1 0 100%;
}
#body-plan,
#current-section,
#rendering {
  flex: 1 0 32%;
}
canvas {
  flex: auto; /* new addition from answer */
  background: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure id="viewport" class="flex">
  <div id="half-breadth" class="canvas">
    <canvas id="half-breadth-canvas"></canvas>
  </div>
  <div id="profile" class="canvas">
    <canvas id="profile-canvas"></canvas>
  </div>
  <div id="body-plan" class="canvas">
    <canvas id="body-plan-canvas"></canvas>
  </div>
  <div id="current-section" class="canvas">
    <canvas id="current-section-canvas"></canvas>
  </div>
  <div id="rendering" class="canvas">
    <canvas id="rendering-canvas"></canvas>
  </div>
</figure>

至少在 OS X 上的谷歌浏览器中,画布小于包含 div 元素的高度,并且在最后 3 个中,它小于的量每个都不同。如果没有 flex 布局,所有这些都比容器小。有没有办法让它们实际上都完全相同的大小?理想情况下也可以在使用 flex 时进行修复?

此时,我并不关心浏览器的兼容性/可移植性(我使用的是 flex,所以我已经决定生活在最前沿),但我确实需要使用画布属性'我知道,因为我不想扭曲内容(即我不能使用 CSS 100% 宽度/高度)。

更新:将 CSS 添加到代码 sn-p 以反映答案中提供的公认解决方案(请参阅 CSS 中的 cmets)。

【问题讨论】:

    标签: jquery html css canvas


    【解决方案1】:

    canvas 元素不是 viewport 的直接子元素,因此您必须将 display:flex 添加到 .canvas 类并指示 canvas 为 flex:auto

    【讨论】:

    • 我的理解是,这正是 jQuery 使用 height() 函数返回的内容(但是 getComputedStyle 据说性能更高)。无论如何,转换为该建议会产生完全相同的结果。奇怪的是,我还注意到高度随着窗口大小的调整而增加。我认为这与 div 扩展以适应内容有关。
    • 由于画布元素不是视口的直接子元素,您可能需要将 display:flex 添加到 .canvas 类中。
    • 完美!将display: flex 添加到.canvasflex: autocanvas 的组合可以解决所有问题。我认为getComputedStyle/jQuery height() 根本没有影响它。如果您想更新答案以反映 cmets,我会接受。谢谢。
    • 同意,我的 getComputedStyle 脱靶了。我已经改变了我的答案是正确的。祝你的项目好运!
    • getComputedStyle 确实为我指出了更好的代码。一旦我开始转换到那个,我注意到我运行了两次each 循环,而我可以在一个循环中执行这两个操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多