【问题标题】:Canvas Animation To Go To Mouse Coords画布动画转到鼠标坐标
【发布时间】:2015-07-24 21:36:58
【问题描述】:

如何使一个圆移动到类似于游戏http://www.agar.io 的特定坐标对?我已经尝试过 jquery animate() 函数,但它的速度很慢,因为我希望圆圈移动到的坐标会不断更新。

【问题讨论】:

标签: javascript html canvas jquery-animate


【解决方案1】:

agar.io 仅使用核心画布功能。

这是一个跟随光标显示球的示例。

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;
}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-27
    • 2011-10-15
    • 2015-03-13
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多