HTML5 Game - Following the mouse

Description

Following the mouse

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
  <head>
    <title>Chapter 2 - Basics of Canvas</title>
  </head>//w  w  w.j a va 2s.  c o  m

  <body>
    <canvas id="animation">
      <p>Fallback not supported.</p>
    </canvas>
    <script>
      // Pollyfill for RequestAnimationFrame
(function() {
  let requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                              window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();


let ele = document.querySelector("#animation");
let ctx = ele.getContext('2d');
let width = height = 50;
let startX = 10;
let startY = 10;
let endX;
let x = startX;
let y = startY;
let duration = 0;

function logic (evt) {
  let max = ele.width - width;
  duration += 0.02;
  let l = lerp(startX, endX, duration);
  if (l < max && l > 0 && endX != x)
  { 
    x = l;
    requestAnimationFrame(draw);
  }
  else {
    duration = 0;
  }
}

function draw()  {  
    ctx.clearRect(0, 0, ele.width, ele.height);
  
  // This sets the fill colour to red
  ctx.fillStyle = "#ff0000";

  // fillRectangle(x, y, width, height);
  ctx.fillRect(x, y, 50, 50);
}

function lerp(start, end, speed) {
  return start + (end - start) * speed;
}

ele.addEventListener('mousemove', function(evt) {
  startX = x;
  endX = evt.clientX;
});

requestAnimationFrame(draw);
setInterval(logic, 1000/60);
      </script>
  </body>
</html>

Related Topics