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.
I have visualized in this fiddle how the setup would look. I replaced the ws side with manual button input for this test purpose but its missing the function to move the circle.
jQuery is welcome too.
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();
https://jsfiddle.net/1g18rsqy/
Thanks :)
You can calculate the delta time between the current time of your animation, and its starting time. Then, you just have to move your circle by the difference between its original position and its next position, multiplied by this delta time :
You can get this
time
directly from the argument passed inrequestAnimationFrame
callback.