RetsuWolf
RetsuWolf

Reputation: 1

Canvas Animation To Go To Mouse Coords

How to animate a circle that goes to a specific pair of coordinates similar to the game http://www.agar.io ? I've already tried the jquery animate() function but it's slow as crap because the coordinates that I want the circle to move to are constantly being updated.

Upvotes: 0

Views: 858

Answers (1)

user2072826
user2072826

Reputation: 536

agar.io uses only core canvas functions.

Here is an example to show a ball following your cursor.

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 500;
ctx.canvas.height = 500;
var V2 = function(x, y) {
  this.x = x;
  this.y = y;
};
var cursor = new V2(0, 0);
var ballSize = 20;
var ball = new V2(0, 0);
ctx.DrawGrid = function(size) {
  this.fillStyle = "black";
  for (var x = 0; x != 25; x++)
    for (var y = 0; y != 25; y++)
      this.strokeRect(x * size, y * size, size, size);
}
var main = setInterval(function() {
  ctx.clearRect(0, 0, 5000, 5000);

  if (cursor.x > ball.x - ballSize)
    ball.x += 3;
  if (cursor.y > ball.y - ballSize)
    ball.y += 3;
  if (cursor.x < ball.x + ballSize)
    ball.x -= 3;
  if (cursor.y < ball.y + ballSize)
    ball.y -= 3;

  if (ball.x < ballSize)
    ball.x = ballSize;
  if (ball.y < ballSize)
    ball.y = ballSize;
  if (ball.x > ctx.canvas.width - ballSize)
    ball.x = ctx.canvas.width - ballSize;
  if (ball.y > ctx.canvas.height - ballSize)
    ball.y = ctx.canvas.height - ballSize;


  ctx.DrawGrid(50);
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ballSize, 0, 2 * Math.PI);
  ctx.fill();

}, 33);

document.onmousemove = function(e) {
  cursor.x = e.pageX;
  cursor.y = e.pageY;
}
html,
body {
  margin: 0px;
}
<canvas id="canvas"></canvas>

Upvotes: 1

Related Questions