Find Point In Segment

Description: This function, when given two points and a percentage value, finds a the point that is percentage distance between the two points. For instance, if you specify 50% it will find the midpoint between the two points. If you give it 25% it will find the point which is a quarter of the way from the start to the end point.
Tested Platform: All Modern Browsers
Language: JavaScript
// Finds the point which is percentage between the two specified points x1,y1 and x2,y2.
// This can also be used to find points that are beyond the bounds of the segment as well.
// Percentages accepted are typically 1 - 100
// Returns an object literal with an .x and .y property. (A Point)

function findPointInSegment(x1, y1, x2, y2, percentage) {
    var newX = (x1 + ((percentage / 100) * (x2 - x1)));
    var newY = (y1 + ((percentage / 100) * (y2 - y1)));
        
    return {x: newX, y: newY};
}

Submitted: March 19, 2013

Return to the snippets listing