How do I get the line to stop at the edge?

Hi, I’ve been trying to draw a blue line like the one shown in the image that passes through 2 given points (red points) and ends as soon as it touches the black line (which i know the x position of but I dont know the y position of the green point). I managed to get the line to pass through both points by using the code below as an example. However the line continues going till the end of the page (like the dotted blue part) and when I change the x position to the one I want it to be, the line shifts completely like the yellow line in the picture and stops passing from the red points. I’m not sure what I need to do to keep it passing through the two red points but stopping at the x position I want it to stop at. (green point)

x1 //first circle's x
y1 //first circle's y
x2 //second circle's x
y2 //second circle's y
//draw a line from top to bottom if the line is vertical, prevents division by 0
if x1 == x2
  line(x1, 0, x1, height)
  return
m = (y2 - y1) / (x2 - x1) // rise / run, gives us the line slope
b = y1 - m * x1 // solves offset by assuming it's 0 and accounting for the error at X=x1
line(0, b, width, m * width + b) //draw a line starting at (0, f(0)) and ending at (width, f(width)) for the line equation

Hi, @chaotic.rabbit,

Is the black line vertical? This suggests that it is:

  line(x1, 0, x1, height)

What is the value of x1? That would help us find the value of y where the two lines touch each other.

EDIT (2x on December 3, 2021):

Is this what you are trying to do?:

two_lines

p5.js code:

function setup() {
  createCanvas(200, 200);
  noLoop();
}

function draw() {
  strokeWeight(4);
  
  // vertical line // x coordinate is constant
  let x_vert = 40;
  stroke(0, 0, 0);
  background(220);
  line(x_vert, 0, x_vert, height);
  
  // define oblique line via two points
  stroke(255, 0, 0);
  let x1 = 80;
  let y1 = 110;
  // mark point 1
  ellipse(x1, y1, 10, 10);
  let x2 = 130;
  let y2 = 60;
  // mark point 2
  ellipse(x2, y2, 10, 10);
  let m_and_b = get_m_and_b(x1, y1, x2, y2);
  let m = m_and_b[0];
  let b = m_and_b[1];
  let y_at_intersection = get_y(m, x_vert, b);
  stroke(0, 255, 0);
  // mark intersection point
  ellipse(x_vert, y_at_intersection, 10, 10);
  
  // draw oblique line; stop at vertical line
  let other_x = 160;
  let other_y = get_y(m, other_x, b);
  stroke(0, 0, 255);
  line(other_x, other_y, x_vert, y_at_intersection);
}

function get_m_and_b(x1, y1, x2, y2) {
  // get slope and y-intercept from 2 points
  if (x1 == x2) {
    return [false, false]; // slope is infinite
  }
  let m = (y1 - y2) / (x1 - x2);
  let b = y1 - m * x1;
  return [m, b];
}

function get_y(m, x, b) {
  // get y from slope, x, and y-intercept
  return m * x + b;
}