Search code examples
javascriptcanvasonmouseover

Make "ball" follow mouse on canvas


I'm trying to make a ball follow the mouse around inside a canvas area. But the ball only get the first position when mouse enter the canvas area (so on the edges).

What is wrong since the ball doesn't follow mouse when moving around inside canvas?

window.onload = startup;

var ballX = 400;
var ballY = 400;
var mouseX = 0;
var mouseY = 0;

function startup() {
  document.getElementById("drawingArea").onmouseover = mouseMove;
  setInterval("moveBall()", 100);
}

function mouseMove(evt) {
  mouseX = evt.clientX;
  mouseY = evt.clientY;
}

function moveBall() {
  if (ballX > mouseX) {
    ballX -= 5;
  } else {
    ballX += 5;
  }
  if (ballY > mouseY) {
    ballY -= 5;
  } else {
    ballY += 5;
  }

  var canvas = document.getElementById("drawingArea");
  var ctx = canvas.getContext("2d");

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.beginPath();
  ctx.arc(ballX, ballY, 40, 0, 2* Math.PI);
  ctx.fillStyle = "green";
  ctx.fill();
  ctx.lineWidth = 5;
  ctx.strokeStyle = "red";
  ctx.stroke();
}
#drawingArea {
  border-style: solid;
  position: absolute;
  top: 0;
  left: 0;
}
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Move Ball</title>
  </head>

  <body>
    <canvas id="drawingArea" width="800" height="800" />
  </body>
</html>


Solution

  • On this line:

    document.getElementById("drawingArea").onmouseover = mouseMove;
    

    ...you need to change onmouseover to onmousemove. Further reading: onmousemove

    Full example with the change:

    			window.onload = startup;
    			var ballX = 400;
    			var ballY = 400;
    			var mouseX = 0;
    			var mouseY = 0;
    			
    			function startup() {
    				document.getElementById("drawingArea").onmousemove = mouseMove;
    				setInterval("moveBall()",100);
    			
    			}
    			
    			function mouseMove(evt) {
    				mouseX = evt.clientX;
    				mouseY = evt.clientY;
    			}
    			
    			function moveBall() {
    				if (ballX > mouseX) {
    					ballX -= 5;
    				} else {
    					ballX += 5;
    				}
    				if (ballY > mouseY) {
    					ballY -= 5;
    				} else {
    					ballY += 5;
    				}
    				
    				var canvas = document.getElementById("drawingArea");
    				var ctx = canvas.getContext("2d");
    				
    				ctx.clearRect(0, 0, canvas.width, canvas.height);
    				
    				ctx.beginPath();
    				ctx.arc(ballX, ballY, 40, 0, 2* Math.PI);
    				ctx.fillStyle = "green";
    				ctx.fill();
    				ctx.lineWidth = 5;
    				ctx.strokeStyle = "red";
    				ctx.stroke();
    			}
    #drawingArea 
    {
    				border-style: solid;
    				position: absolute;
    				top: 0;
    				left: 0;
    }
    <!doctype html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title>Move Ball</title>
    	</head>
    
    	<body>
    		<canvas id="drawingArea" width="800" height="800" />
    	</body>
    </html>