Monday, November 16, 2015

HTML: Canvas background

To have a canvas as a html page background we need:

HTML:

<body onload="load()">
  <canvas id="canvas_back"></canvas>
  ...
</body>

CSS:

#canvas_back {
  position: fixed;
  top: 0px;
  left: 0px;
  z-index: -1;
}

JavaScript:

var c, w, h;

function load() {
  var canvas = document.getElementById("canvas_back");
  c = canvas.getContext("2d");

  window.addEventListener('resize', resize, false);
  resize();
}

function resize() {
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;
  draw();
}

function draw() {
  // use c, w and h to draw the canvas
  ...
  requestAnimationFrame(draw);
}


Demo 1


done_