Canvas How to - Chase the mouse








Question

We would like to know how to chase the mouse.

Answer


<!--from  w  w  w  .j  av a 2  s . co  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas=document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = canvas.height = 500;
var targetX = 0,targetY = 0;
var x = 10, y = 10;
var velX = 0, velY = 0;
var speed = 5;
function update(){
    var tx = targetX - x,
        ty = targetY - y;
    var dist = Math.sqrt(tx*tx+ty*ty);
    var rad = Math.atan2(ty,tx),
        angle = rad/Math.PI * 180;
    var velX = (tx/dist)*speed,
        velY = (ty/dist)*speed;
        x += velX
        y += velY
        ctx.clearRect(0,0,500,500);
        ctx.beginPath();
        ctx.arc(x,y,5,0,Math.PI*2);
        ctx.fill();
    setTimeout(update,10);
}
update();
canvas.addEventListener("mousemove", function(e){
    targetX = e.pageX;
    targetY = e.pageY;
});
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: