HTML canvas move circle from a to b with animation

Jac*_* M. 1 html javascript animation canvas

I was wondering what would be the best way to move a circle from point A to point B using smooth animation.

I get new coordinates with websocket every second and would like to animate the circle move from last point to the new point during that second.

我已经在这个小提琴中看到了设置的外观。为了这个测试,我用手动按钮输入代替了ws侧,但是缺少了移动圆环的功能。

jQuery也很受欢迎。

var x = 100;
var y = 50;
var r = 10;

var WIDTH = 600;
var HEIGHT = 400;

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

function circle(x, y, r) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2, true);
  ctx.fill();
}

function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function draw() {
  clear(WIDTH, HEIGHT);
  ctx.fillStyle = "purple";
  circle(x, y, r);
}

draw();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/1g18rsqy/

谢谢 :)

Kai*_*ido 5

您可以计算当前动画时间与其开始时间之间的增量时间。然后,您只需要按原点位置与下一个位置之间的差值乘以此增量时间来移动圆:

var deltaTime = (currentTime - startTime) / duration;
var currentX = prevX + ((nextX - prevX) * deltaTime);
Run Code Online (Sandbox Code Playgroud)

您可以time直接从requestAnimationFrame回调中传递的参数中获取此信息。

var deltaTime = (currentTime - startTime) / duration;
var currentX = prevX + ((nextX - prevX) * deltaTime);
Run Code Online (Sandbox Code Playgroud)
var x = 100;
var y = 50;
var r = 10;
var duration = 1000; // in ms
var nextX, nextY;
var startTime;

function anim(time) {
  if (!startTime) // it's the first frame
    startTime = time || performance.now();

  // deltaTime should be in the range [0 ~ 1]
  var deltaTime = (time - startTime) / duration;
  // currentPos = previous position + (difference * deltaTime)
  var currentX = x + ((nextX - x) * deltaTime);
  var currentY = y + ((nextY - y) * deltaTime);

  if (deltaTime >= 1) { // this means we ended our animation
    x = nextX; // reset x variable
    y = nextY; // reset y variable
    startTime = null; // reset startTime
    draw(x, y); // draw the last frame, at required position
  } else {
    draw(currentX, currentY);
    requestAnimationFrame(anim); // do it again
  }
}

move.onclick = e => {
  nextX = +x_in.value || 0;
  nextY = +y_in.value || 0;
  anim();
}

// OP's code

var WIDTH = 600;
var HEIGHT = 400;

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

function circle(x, y, r) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2, true);
  ctx.fill();
}

function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function draw(x, y) {
  clear(WIDTH, HEIGHT);
  ctx.fillStyle = "purple";
  circle(x, y, r);
}

draw(x, y);
Run Code Online (Sandbox Code Playgroud)
#canvas {
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)