Make image follow mouse with ease in HTML5 Canvas - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Make image follow mouse with ease in HTML5 Canvas

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){//from w ww  .  ja v  a2 s .co  m
var AN = AN || {};
var pic = new Image();
var canvas;
var context;
var x = 0;
var y = 0;
AN.initialize = function() {
  //load canvas
  canvas = $('#canvas');
  canvas.mousemove(AN.moveMouse);
  context = canvas[0].getContext('2d');
  //load image
  pic.src = "https://www.java2s.com/style/demo/Google-Chrome.png";
};
AN.moveMouse = function (e) {
  var element = $(pic);
  var t = 0; //0-1, this is what you change in animation loop
  var position = getMousePosition(e);
  function myLoop() {
    context.clearRect(0, 0, canvas.width(), canvas.height());
    x += EasingFunctions.easeInOutQuad(t) * (position.x - x);
    y += EasingFunctions.easeInOutQuad(t) * (position.y - y);
    context.drawImage(pic, x, y, pic.width, pic.height);
    if (t < 1) {
      t += 0.01; //determines speed
      requestAnimationFrame(myLoop);
    }
  }
  myLoop();
};
EasingFunctions = {
  linear: function(t) {
    return t;
  },
  easeInQuad: function(t) {
    return t * t;
  },
  easeOutQuad: function(t) {
    return t * (2 - t);
  },
  easeInOutQuad: function(t) {
    return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  },
  easeInCubic: function(t) {
    return t * t * t;
  },
  easeOutCubic: function(t) {
    return (--t) * t * t + 1;
  },
  easeInOutCubic: function(t) {
    return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  },
  easeInQuart: function(t) {
    return t * t * t * t;
  },
  easeOutQuart: function(t) {
    return 1 - (--t) * t * t * t;
  },
  easeInOutQuart: function(t) {
    return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
  },
  easeInQuint: function(t) {
    return t * t * t * t * t;
  },
  easeOutQuint: function(t) {
    return 1 + (--t) * t * t * t * t;
  },
  easeInOutQuint: function(t) {
    return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
  }
}
function getMousePosition(e) {
    return {
        x: e.clientX - pic.width * 0.5,
        y: e.clientY - pic.height * 0.5
    }
}
$(document).ready(function() {
  AN.initialize();
});
    });

      </script> 
   </head> 
   <body> 
      <section id="main"> 
         <canvas id="canvas" width="1000px" height="1000px" style="background:red">
            Upgrade to modern browser in order to see this painting ;)
         </canvas> 
      </section>  
   </body>
</html>

Related Tutorials