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

上一篇:jquery - 用 jquery 包装第 n 个 child

下一篇:jquery - 单击新 div 时切换另一个 div 的类。查询

相关文章:

html - 开始滚动后背景被切断?

javascript - 在我的案例中如何在指令中分配数据

javascript - 在html Canvas 上绘制贝塞尔曲线

html - 使 960 像素宽的网站适合移动设备

html - 导航栏与 Logo 对齐

javascript - 如何在移动 View css 中相互交换 div

javascript - 如何在不同方向多次绘制一张图像?

javascript - 与 Angular typescript 一起使用时,类型 'GlobalEventHandlers' 上不存在属性 classList

javascript - 检测追加后div的长度

html5-canvas - html5 线模糊且未售出