Bear in mind that requestAnimationFrame()
does not have any mechanism for passing parameters into your named function. A simple way to deal with that is to put some more properties on the global DATA
. I like to group them together as animData
, setting it up something like this:
let nSteps = 50;
let dx = (end.x - start.x) / nSteps;
let dy = (end.y - start.y) / nSteps;
DATA.animData =
{obj:oneOfOurShapes, dx:dx, dy:dy, nSteps:nSteps, step:0};
Then the function that does the animation would be like this:
function animate()
{
let ad = DATA.animData;
ad.obj.x += ad.dx;
ad.obj.y += ad.dy;
draw(); // draw everything
ad.step++;
if (ad.step < ad.nSteps)
{
requestAnimationFrame(animate);
}
}
(a += b
is standard shorthand for a = a + b
)