Interpolate Points on a Line


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function lineInterpolate( point1, point2, distance )
  2. {
  3. var xabs = Math.abs( point1.x - point2.x );
  4. var yabs = Math.abs( point1.y - point2.y );
  5. var xdiff = point2.x - point1.x;
  6. var ydiff = point2.y - point1.y;
  7.  
  8. var length = Math.sqrt( ( Math.pow( xabs, 2 ) + Math.pow( yabs, 2 ) ) );
  9. var steps = length / distance;
  10. var xstep = xdiff / steps;
  11. var ystep = ydiff / steps;
  12.  
  13. var newx = 0;
  14. var newy = 0;
  15. var result = new Array();
  16.  
  17. for( var s = 0; s < steps; s++ )
  18. {
  19. newx = point1.x + ( xstep * s );
  20. newy = point1.y + ( ystep * s );
  21.  
  22. result.push( {
  23. x: newx,
  24. y: newy
  25. } );
  26. }
  27.  
  28. return result;
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.