1
votes

How to implement animated background with html5 canvas? I want to add mouse events for this animation. I have issues with text over background because it vanishes during painting on canvas. Handling with z-coordinate doesn't work correctly.

1
Might want to accept some previous answers, and also post some code. Using a simple sort in a rendering loop based on a z property should work. - Loktar
The question is pretty vague, but have you looked into canvas libraries like fabric.js? - kangax
There are at least five questions in there: how to draw to the canvas, how to animate with the canvas, how to handle mouse events with the canvas, how to write text to the canvas, how to float HTML elements over the canvas. - puk

1 Answers

1
votes

Animated background with canvas

Okay, so by sounds of it, you might want to check out MDN by finding a page that interests you (like the canvasRenderingContext2d page), and start reading from there (you'll learn ALOT really fast). But, getting back to the point of this post, what I would recommend (judging from the issues you listed there) is:

  • Check the cursor position via the window's cursor events.
  • Clear the canvas every time you draw if drawing aliases are an issue due to canvas transparency.
  • Use requestAnimationFrame to help the browser with scheduling canvas redrawing.

An demo example of such an implementation is shown below. In the below example, coordinates of your cursor are displayed at your cursors location, with a yellow dot background relative to your cursors position to the center of the page. Enjoy!

var bgcanvas = document.getElementById('backgroundCanvas'),
    bgcontext = bgcanvas.getContext('2d'),
    mouseX = 0,
    mouseY = 0,
    mouseChanged = false;

window.addEventListener('mousemove', function(evt){
  if (mouseX !== evt.clientX)
    mouseX = evt.clientX, mouseChanged = true;
  if (mouseY !== evt.clientY)
    mouseY = evt.clientY, mouseChanged = true;
});

var repaintBGcanvasCUR = 0;
var repaintBGcanvas = function(){
  requestAnimationFrame(repaintBGcanvas);
  if ((++repaintBGcanvasCUR%2) // only modify the canvas half the time to reduce the CPU strain
      && mouseChanged){ // if the mouse has changed
    mouseChanged = false;
    bgcontext.clearRect(
      0,0,bgcanvas.width,bgcanvas.height);
    bgcontext.beginPath();
    // create the yellow circle path:
    bgcontext.arc(mouseX, mouseY, 
      // pythagorean theorem:
      Math.hypot(mouseX-bgcanvas.width/2, mouseY-bgcanvas.height/2)/4,
      0, 2 * Math.PI);
    bgcontext.closePath();
    bgcontext.fillStyle = "rgba(255,255,0,.5)";
    // fill in the yellow circle
    bgcontext.fill();
    bgcontext.textAlign = 'center'; // horozontally center the text
    bgcontext.textBaseline = 'middle'; // vertically center the text
    bgcontext.font = '48px monospace'; // make the text fancy
    bgcontext.fillStyle = 'red'; // make the text fancy
    bgcontext.fillText( mouseX + ' X ' + mouseY, mouseX, mouseY);
  }
}
window.addEventListener(
  'load', repaintBGcanvas );

var resizeBackgroundCanvas = function(){
  bgcanvas.width = window.innerWidth;
  bgcanvas.height = window.innerHeight;
}
window.addEventListener(
  'resize', resizeBackgroundCanvas );
window.addEventListener(
  'load', resizeBackgroundCanvas );

// speed up canvas:
bgcontext.imageSmoothingEnabled = false;
html, body, #backgroundCanvas {
  width: 100%;
  height: 100%;
  margin: 0;
  cursor: none;
}
#backgroundCanvas {
  z-index: -2147483647; /*maximum far back*/
  position: fixed;
  top: 0; left: 0;
}
p {
  margin: 3em 2em;
}
<canvas id="backgroundCanvas"></canvas>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>