Let me provide another solution by adding a new answer:
canvas {
width: 100vw;
height: 100vh;
display: block;
position: fixed;
top: 0;
left: 0;
z-index: -9999;
}
Here's the reasoning behind this approach:
Instead of using
canvas { width: 100%; height: 100% }
, which might not be ideal as it makes the canvas take up 100% of the body, consider using
canvas { width: 100vw; height: 100vh; }
. This sets the canvas dimensions to be 100% of the viewport width and height.
By utilizing these values, there is no need to set the body to have a height of 100%, especially when the page exceeds the window or screen height.
The use of display: block;
helps address scrollbar issues on certain browsers, eliminating the need for declarations like html, body { overflow: none; }
, which may cause problems if the page extends beyond the window.
Setting position: fixed;
ensures that the canvas remains in place relative to the top of the window, preventing it from scrolling along with the page. In contrast, using position: absolute
would cause the canvas to scroll off the screen if the page is taller than the window.
Placing top: 0; left 0;
positions the canvas at the top left corner instead of defaulting to its position within the body's margins. While setting body { margin: 0; }
can help align content with the window edge, it often requires additional containers to manage spacing.
Adding z-index: -9999;
attempts to push the canvas further back than other elements, especially if the page utilizes negative z-index
values elsewhere.
An interactive snippet example is provided below:
Note that interactive canvas animations may face challenges with front elements intercepting mouse/touch events. Adjusting pointer-events
properties can impact text selection and link functionality, requiring careful consideration based on your page's content.
It's worth mentioning that many three.js examples refer to window.innerWidth
and
window.innerHeight</code, placing the canvas within an <code><div>
element with an
id="canvas"
. The structure may differ slightly in implementation but offers similar functionality for sizing.