UNPKG

transcend-charts

Version:

Transcend is a charting and graph library for NUVI

80 lines (67 loc) 2.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { doLinesCross: function doLinesCross(line1, line2) { // the coordinates where the lines intersect var x = undefined; var y = undefined; // special case for vertical line1 if (line1.x2 - line1.x1 === 0) { if (line2.x2 - line2.x1 === 0) { if (line1.x1 === line2.x1) { return true; // colinear verticals } return false; } var m2 = (line2.y2 - line2.y1) / (line2.x2 - line2.x1); var b2 = line2.y1 - m2 * line2.x1; x = line1.x1; y = m2 * x + b2; } else if (line2.x2 - line2.x1 === 0) { var m1 = (line1.y2 - line1.y1) / (line1.x2 - line1.x1); var b1 = line1.y1 - m1 * line1.x1; x = line2.x1; y = m1 * x + b1; } else { // get slope and y-intercept for line 1 var m1 = (line1.y2 - line1.y1) / (line1.x2 - line1.x1); var b1 = line1.y1 - m1 * line1.x1; // get slope and y-intercept for line 2 var m2 = (line2.y2 - line2.y1) / (line2.x2 - line2.x1); var b2 = line2.y1 - m2 * line2.x1; // are the lines parallel? if (m1 === m2) { if (b1 === b2) { return true; // colinear - they cross } else { return false; // parallel - never going to touch } } // find where the lines cross x = (b2 - b1) / (m1 - m2); y = m1 * x + b1; } if (x === undefined || y === undefined) { // parallel case that should never happen because it's handled above return false; } // find out which ones are the min and max coordinates line1.minX = Number((line1.x1 < line1.x2 ? line1.x1 : line1.x2).toPrecision(12)); line1.maxX = Number((line1.x1 > line1.x2 ? line1.x1 : line1.x2).toPrecision(12)); line1.minY = Number((line1.y1 < line1.y2 ? line1.y1 : line1.y2).toPrecision(12)); line1.maxY = Number((line1.y1 > line1.y2 ? line1.y1 : line1.y2).toPrecision(12)); line2.minX = Number((line2.x1 < line2.x2 ? line2.x1 : line2.x2).toPrecision(12)); line2.maxX = Number((line2.x1 > line2.x2 ? line2.x1 : line2.x2).toPrecision(12)); line2.minY = Number((line2.y1 < line2.y2 ? line2.y1 : line2.y2).toPrecision(12)); line2.maxY = Number((line2.y1 > line2.y2 ? line2.y1 : line2.y2).toPrecision(12)); x = Number(x.toPrecision(12)); y = Number(y.toPrecision(12)); // test whether the point x,y is within the bounds of the defined line segments if (x >= line1.minX && x <= line1.maxX && y >= line1.minY && y <= line1.maxY && x >= line2.minX && x <= line2.maxX && y >= line2.minY && y <= line2.maxY) { return true; } return false; } };