1

I have set my canvas's height to the window's inner width. Whenever I scroll down, the canvas shifts up a bit revealing a white space. How can I make it that you are unable to scroll down.

//declare variables
var body = document.getElementById("body");
var canvas = document.getElementById("canvas");
var iwidth = window.innerWidth;
var iheight = window.innerHeight;

//puts canvas in top right corner
body.style.margin = "0";

//changes the canvas's style namely color, margin, width and height
canvas.style.backgroundColor = "red";
canvas.style.margin = "0";
canvas.width = iwidth;
canvas.height = iheight;
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>DUNGE</title>
</head>
<body id="body">
 <canvas id="canvas"></canvas>
 <script src="script.js"></script>
</body>
</html>
wifi engine
  • 37
  • 1
  • 6

2 Answers2

1

There is white space under your canvas, because the HTML <canvas> element has a default style of display: inline;. Inline elements are designed to contain text, and therefore white space gets added underneath the element for descenders (the bits that hang off the bottom of 'y' and 'p').

To fix the problem, apply display: block; to the element instead.

Using Javascript, you would do that like this:

canvas.style.display = "block";

//declare variables
var body = document.getElementById("body");
var canvas = document.getElementById("canvas");
var iwidth = window.innerWidth;
var iheight = window.innerHeight;

//puts canvas in top right corner
body.style.margin = "0";

//changes the canvas's style namely color, margin, width and height
canvas.style.backgroundColor = "red";
canvas.style.margin = "0";
canvas.style.display = "block";
canvas.width = iwidth;
canvas.height = iheight;
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DUNGE</title>
</head>
<body id="body">
  <canvas id="canvas"></canvas>
  <script src="script.js"></script>
</body>
</html>

You can also fix the problem by applying font-size: 0; to the canvas, but display: block is better because it is made to do what you want your canvas to do.

See also https://stackoverflow.com/a/5078297/7733026

James Douglas
  • 3,328
  • 2
  • 22
  • 43
-1
var body = document.getElementById("body");
var canvas = document.getElementById("canvas");
var iwidth = window.innerWidth;
var iheight = window.innerHeight;

body.style.margin = "0";
canvas.style.backgroundColor = "red";
canvas.style.margin = "0";
canvas.width = iwidth;
canvas.height = "100vh";

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Page</title>
</head>
<body id="body">
    <canvas id="canvas"></canvas>
    <script src="script.js"></script>
</body>
</html>
Bioukh
  • 1,888
  • 1
  • 16
  • 27