var line1XSlider = document.getElementById('line1XSlider'),
line1YSlider = document.getElementById('line1YSlider'),
line2XSlider = document.getElementById('line2XSlider'),
line2YSlider = document.getElementById('line2YSlider'),
context = document.getElementById('canvas').getContext('2d'),
display = document.getElementById('results');
function checkLineIntersection(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {
var denominator, a, b, numerator1, numerator2, result = {
denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY));
a = line1StartY - line2StartY;
b = line1StartX - line2StartX;
numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b);
numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b);
a = numerator1 / denominator;
b = numerator2 / denominator;
result.x = line1StartX + (a * (line1EndX - line1StartX));
result.y = line1StartY + (a * (line1EndY - line1StartY));
function drawPoint(x, y, color) {
context.fillStyle = color || 'black';
context.arc(x, y, 5, 0, 2 * Math.PI, true);
function drawLine(line, color) {
color = color || 'black';
context.strokeStyle = color;
context.moveTo(line.startX, line.startY);
context.lineTo(line.endX, line.endY);
drawPoint(line.startX, line.startY, color);
drawPoint(line.endX, line.endY, color);
endX: line1XSlider.value,
endX: line2XSlider.value,
context.clearRect(0, 0, 400, 300);
results = checkLineIntersection(line1.startX, line1.startY, line1.endX, line1.endY, line2.startX, line2.startY, line2.endX, line2.endY);
drawPoint(results.x, results.y, 'green');
display.innerHTML = 'x = ' + results.x + '<br />y = ' + results.y + '<br />onLine1 = ' + results.onLine1 + '<br />onLine2 = ' + results.onLine2;
line1XSlider.onchange = update;
line1YSlider.onchange = update;
line2XSlider.onchange = update;
line2YSlider.onchange = update;