9

Is there a way I can make an HTML5 canvas the background of a web page I am making and place all the elements on top of it.

So it acts like the <body>?

I tried doing this with z-index and positioning the elements on top, but then they were click-able or focus-able. I need them to still be functioning, but the canvas to also be clickable just in the background and not clickable where there are elements over it.

alex
  • 479,566
  • 201
  • 878
  • 984
JayGatz
  • 271
  • 1
  • 8
  • 18
  • See also: https://stackoverflow.com/questions/3397334/use-canvas-as-a-css-background/43105694#43105694 – Jonathan Mar 29 '17 at 23:10

2 Answers2

9

Just set the <canvas>'s z-index to -1. If your canvas is covered by containers on top, simulate custom events using createEvent.[1]

Demo: http://jsfiddle.net/DerekL/uw5XU/

var canvas = $("canvas"),  //jQuery selector, similar to querySelectorAll()
//...

function simulate(e) {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("mousemove", true, true, window,
        0, e.screenX, e.screenY, e.clientX, e.clientY, false, false, false, false, 0, null);
    canvas[0].dispatchEvent(evt);
}

$("body > *").each(function () {
    this.addEventListener("mousemove", simulate);
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Ah, okay. I think what I was missing was the custom events. Can you show me an example of how to use custom events to simulate clicking on a canvas when there is actually a container on top? – JayGatz Jun 09 '13 at 06:10
  • If the top layer should be invisible to mouse interactions, set `pointer-events: none`. – alex Jun 09 '13 at 06:26
  • @alex - This is no top layer in my demo... (since I just updated it you might have to reload the page) Nevertheless, this is still a great comment. – Derek 朕會功夫 Jun 09 '13 at 06:29
0

Sure that would be possible with z-index, most probably the canvas will not be clickable because you're working with a container that's on top of it. So even if there appears to be no element the container is still there which prevents you from clicking on the canvas.

user2019515
  • 4,495
  • 1
  • 29
  • 42