1

I'm using this answer https://stackoverflow.com/a/36233727/1350146 to scroll a canvas in a div. I'm also hiding the scrollbar. The problem is it appears to scroll too far, in this case if you scroll down you can see the red of the div the canvas is in.

I've tried messing with padding & margins and different sizes but no luck.

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>

How can I make it scroll just to the end of the canvas and not show any of the container div underneath?

Thanks!

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
John Leonard
  • 909
  • 11
  • 18

2 Answers2

3

Make the canvas a block element or use vertical-align:top. By default, canvas is an inline element and it will behave similary to an img; thus you will have the whitespace issue due to vertical alignement (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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Thanks & thanks for the explanation too, I had noticed in my real-life app the gap was slightly different and the inline link you have above explains it - I had used a different vertical-align for text which places the inline canvas slightly differently – John Leonard Jun 11 '18 at 07:08
1

Use a negative margin-bottom value for your canvas element. Anything between margin-bottom: -5px; and margin-bottom: -105px; will work for this example.

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>
marvinscham
  • 42
  • 1
  • 5