Set HTML Canvas as page background

I’ve made a JS animation that I want to be the background of my homepage: But I’m quite new to web development and unclear how to stop the canvas element being an ‘inline’ object on the page and set it behind other HTML elements. Very grateful for advice. The HTML is:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
        * {
        margin: 0;
        padding: 0;
        h1 {color:#fff;}
        p {color:#fff;}

<body  id="home" bgcolor="black">
    <!-- style="overflow:hidden;" -->
    <p>paragraph 1</p>
    <p>paragraph 2</p>
    <script src="processing-1.4.1.min.js"></script>
    <div id="canvasContainer">
    <canvas data-processing-sources="rectangles.pde"></canvas>


In 2018 I’d use

html, body { 
  margin: 0;
  height: 100%;
canvas {
  width: 100%;
  height: 100%;
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -9999;

Here’s why:

I used to recommend canvas { width: 100vw; height: 100vh; ...} but sadly mobile browsers broke vh so it’s useless and will apparently be useless forever. See this blog post.

display: block; fixes some issues with scrollbars on certain browsers. Some pages use html, body { overflow: none; } but again that doesn’t make sense if your page ends up needing to be taller than the screen/window.

position: fixed; makes the canvas position relative to the top of window so it won’t scroll with the page. If you use position: absolute then the canvas will scroll off the top if the page is taller than the screen/window. For example this page.

top: 0; left 0; puts it at the top left. Without that it would default to it’s default position which is inside the body’s margins. Often this is solved by setting body { margin: 0; } but generally that means you end up needing some other container to add a margin back in otherwise your normal content gets positioned at the edge of the window.

z-index: -9999; is there to try to force it further back than anything else just in case the page itself is using some negative values for z-index

Here’s an example as a snippet

And here’s an example outside SO so you can view it easier full size.

iframes work as well

Note that there’s the issue that if your canvas animation is interactive the elements in front of the canvas will eat the mouse/touch events. There’s no easy solution I know of for that. You can mark everything but that canvas/iframe as pointer-events: none and mark the canvas/iframe as pointer-events: auto but then you run into the issue that no text on your page can be selected and no links can be clicked. You could then say set <a> tags to have pointer-events: auto so links work but I’m sure there will be issues here and there depending on what info is on your page (trying to copy an email address, or a location address, etc…)

Source : Link , Question Author : geotheory , Answer Author : gman

Leave a Comment