Drawing a point from the slope of two points in the Cartesian plane
This is not a math tutorial. See Why am I writing about math?
Related to notes / Drawing dotted lines between points with Processing.
Get the rise by subtracting the y value of point “a” from the y value of point “b”. Get the
run by subtracting the x value of point “a” from the x value of point “b”. Get the slope by
dividing rise/run.
The slope is the ratio of rise over run. If the slope is known, a new y value that falls on the
line can be calculated for any run.
size(400, 400);
textSize(8);
background(235);
fill(25);
translate(width/2, height/2);
scale(1, -1);
int x1 = -123;
int y1 = -44;
int x2 = 157;
int y2 = 99;
int rise = y2 - y1;
int run = x2 - x1;
float slope = float(rise)/float(run);
pushMatrix();
scale(1, -1);
text("slope: " + str(slope), -width/2 + 8, -height/2 + 8);
popMatrix();
strokeWeight(8);
stroke(158, 41, 28);
point(x1, y1);
stroke(46, 28, 158);
point(x2, y2);
float xOffset = 111;
float calculatedX = float(x1) + xOffset;
float calculatedY = float(y1) + slope * xOffset;
stroke(50, 168, 82);
point(calculatedX, calculatedY);
// visually confirm
stroke(122);
strokeWeight(1);
line(x1, y1, x2, y2);
A dynamic version
Sets the x and y values of the calculated point with the mouseDragged() event:
int x2 = 0;
int y2 = 0;
void setup() {
size(400, 400);
textSize(8);
background(235);
fill(25);
}
void draw() {
translate(width/2, height/2);
scale(1, -1);
background(235);
int x1 = -173;
int y1 = -184;
strokeWeight(8);
stroke(158, 41, 28);
point(x1, y1);
stroke(46, 28, 158);
point(x2, y2);
int rise = y2 - y1;
int run = x2 - x1;
float slope = float(rise)/float(run);
float xOffset = 100;
float calculatedX = float(x1) + xOffset;
float calculatedY = float(y1) + xOffset * slope;
stroke(50, 168, 82);
point(calculatedX, calculatedY);
// confirm
strokeWeight(1);
stroke(165);
line(x1, y1, x2, y2);
pushMatrix();
scale(1, -1);
stroke(125);
text("slope: " + str(slope), -width/2 + 8, -height/2 + 8);
popMatrix();
}
void mouseDragged() {
x2 = mouseX - width/2;
y2 = -1 * (mouseY - height/2);
}
A limitation of relying on the slope to set the new point
The new point is being calculated from the slope some new run value. For example, if the run is 50, the
new x is originalX1 + run, the new y is originalY1 + run * slope. This doesn’t make it
possible to accurately do something like always have the new point halfway between the original
points. There’s a solution to this problem in
notes / Drawing a point from the parametric representation of a
line.