JSFiddle - React, Tailwind, and code Playground

by sampottinger

HTML

<canvas id="target-canvas">
</canvas>

JavaScript

var path = [
  {pos: [0,0], time:0},
  {pos: [50,50], time:100},
  {pos: [100,50], time:200}
];

var time = 0;
var ctx = $("#target-canvas")[0].getContext("2d");
setInterval(drawScene, 10);

function linearInterpolate(x1, x2, y1, y2, x3)
{
  return y1 + (y2 - y1) * ((x3 - x1)/(x2-x1));
}

function getPos(time)
{
  var lastTimePoint = null;
  var targetTimePoint = null;
  
  // Find point we should be going to
  for(var i=0; i<path.length; i++)
  {
    var possibleTimePoint = path[i];
    if(possibleTimePoint.time > time)
      targetTimePoint = possibleTimePoint;
    else
      lastTimePoint = possibleTimePoint;
  }
  
  // Find if we got past the end of the path
  if(targetTimePoint == null)
    return null;
  
  // Linear interpolate between points
  var x1 = lastTimePoint.pos[0];
  var y1 = lastTimePoint.pos[1];
  var x2 = targetTimePoint.pos[0];
  var y2 = targetTimePoint.pos[1];
  var time1 = lastTimePoint.time;
  var time2 = targetTimePoint.time;
  
  var targetX = linearInterpolate(time1, time2, x1, x2, time);
  var targetY = linearInterpolate(time1, time2, y1, y2, time);
  
  return [targetX, targetY];
}

function drawObj(ctx, x, y)
{
  ctx.fillStyle = 'white';
  ctx.fillRect(x, y, 10, 10);
}

function drawScene()
{
  time+=1;
  if(time >= 200)
    time = 0;

  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, 300, 300);

  var pos = getPos(time);
  console.log(pos);
  drawObj(ctx, pos[0], pos[1]);
}