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/50784177/

相关文章:

javascript - 在 Canvas 上寻找定制(加入 div 并保持它的关系)

javascript - 重绘相同的 Canvas 线条不准确

javascript - 使用 requestAnimationFrame 而不是 setInterval

html - 固定导航菜单内容在放大时不随页面水平滚动

css - 如何在 IE 7 中使用 HTML5?

javascript - 如何向该 Canvas 球添加图像?

CSS 根据关键变量调整大小

javascript - 如何将文本和 Div 放置在彼此的顶部并将它们居中对齐?

jquery - 带有标题显示表的 slider

html - 水平居中绝对元素