css - Canvas 底部有空白,滚动得太远

标签 css html html5-canvas

我正在使用这个答案 https://stackoverflow.com/a/36233727/1350146在 div 中滚动 Canvas 。我也隐藏了滚动条。问题是它似乎滚动得太远,在这种情况下,如果向下滚动,您可以看到 Canvas 所在 div 的红色。

我试过弄乱填充和边距以及不同的尺寸,但没有运气。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = '#00aa00'
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = '#fff'
ctx.font='12pt A'
ctx.fillText("scroll here to see red from screen div", 30, 50);
.screen {
  background: red;
  height: 100px;
  width: 300px;
  overflow: auto;
  border-radius: 20px;
  
}

::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
<div class="screen">
  <canvas id="myCanvas" width="300" height="120">
  </canvas>
</div>


我怎样才能让它滚动到 Canvas 的末尾而不显示下面的任何容器 div?

谢谢!

最佳答案

将 Canvas 设为 block元素或使用 vertical-align:top .默认情况下,canvas 是一个内联元素,它的行为类似于 img ;因此,由于垂直对齐,您将遇到空格问题( Image inside div has extra space below the image )

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = '#00aa00'
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = '#fff'
ctx.font='12pt A'
ctx.fillText("scroll here to see red from screen div", 30, 50);
.screen {
  background: red;
  height: 100px;
  width: 300px;
  overflow: auto;
  border-radius: 20px;
}
canvas {
 display:block;
}

::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
<div class="screen">
  <canvas id="myCanvas" width="300" height="120">
  </canvas>
</div>

关于css - Canvas 底部有空白,滚动得太远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442497/

相关文章:

javascript - 使用 Canvas API 时有哪些典型的设计模式?

css - 具有 flex 的全页/ chalice 布局

html - 3 div 容器不垂直对齐

javascript - 如何通过<th>值获取表<td>内容

html - 将 Bootstrap 容器背景扩展到页面边缘

javascript - 使用 ASP.NET 在服务器上将 HTML 5 Canvas 保存为图像

jquery - 模糊的字体,动态生成的 SVG 中的线条到 Canvas 中

html - 自定义单选按钮边框颜色

html - 如何更改 :active link color Twitter Bootstrap

css - 将 flash 转换为 html5 后对齐内容时出现问题