Return to Snippet

Revision: 39284
at January 16, 2011 04:21 by parkerkrhoyt


Initial Code
function lineInterpolate( point1, point2, distance )
{
  var xabs = Math.abs( point1.x - point2.x );
  var yabs = Math.abs( point1.y - point2.y );
  var xdiff = point2.x - point1.x;
  var ydiff = point2.y - point1.y;

  var length = Math.sqrt( ( Math.pow( xabs, 2 ) + Math.pow( yabs, 2 ) ) );
  var steps = length / distance;
  var xstep = xdiff / steps;
  var ystep = ydiff / steps;

  var newx = 0;
  var newy = 0;
  var result = new Array();

  for( var s = 0; s < steps; s++ )
  {
    newx = point1.x + ( xstep * s );
    newy = point1.y + ( ystep * s );
            
    result.push( {
      x: newx,
      y: newy
    } );
  }

  return result;
}

Initial URL


Initial Description
This function will interpolate the points on a line.  When tracking mouse movements, not every point is captured.  This is especially true the faster the mouse moves.  This function will allow you to fill in the gap of points between two recorded positions.  It takes two point values (object with an "x" and a "y" property) and the distance to move forward for each new point to be added (e.g. spacing).  The result is an array containing all the points between the two points provided in the function call.

Initial Title
Interpolate Points on a Line

Initial Tags
path, line

Initial Language
JavaScript