画布滚动太远

时间:2018-06-10 13:27:59

标签: css html5 html5-canvas

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

我已经尝试过使用padding& amp;利润和不同的规模,但没有运气。



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>
&#13;
&#13;
&#13;

如何让它滚动到画布的末尾并且不显示下面的任何容器div?

谢谢!

2 个答案:

答案 0 :(得分:2)

将画布设为block元素。默认情况下,canvas是一个内联元素,它的行为类似于img;因此,由于垂直对齐(Image inside div has extra space below the image

,您将遇到空白问题

&#13;
&#13;
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);
&#13;
.screen {
  background: red;
  height: 100px;
  width: 300px;
  overflow: auto;
  border-radius: 20px;
}
canvas {
 display:block;
}

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

答案 1 :(得分:1)

为canvas元素使用负边距底值。 margin-bottom: -5px;margin-bottom: -105px;之间的任何内容都适用于此示例。

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;
}

canvas {
  margin-bottom: -5px;
}
<div class="screen">
  <canvas id="myCanvas" width="300" height="120">
  </canvas>
</div>