xxxxxxxxxx
85
const SIZE = 6;
var line1 = null;
var line2 = null;
var colPoint = null;
var currPoint = null;
function setup() {
createCanvas(400, 400);
line1 = [createVector(300, 300), createVector(250, 350)];
line2 = [createVector(150, 100), createVector(200, 320)];
colPoint = createVector(-SIZE, -SIZE);
}
function draw() {
background(220);
if (mouseIsPressed) {
let mousePos = createVector(mouseX, mouseY);
if (currPoint) {
currPoint.x = mousePos.x;
currPoint.y = mousePos.y;
} else
for (let i = 0; i < 2; i++) {
let diff = p5.Vector.sub(line1[i], mousePos);
if ((diff.x * diff.x) + (diff.y * diff.y) < SIZE * SIZE) {
currPoint = line1[i];
break;
}
diff = p5.Vector.sub(line2[i], mousePos);
if ((diff.x * diff.x) + (diff.y * diff.y) < SIZE * SIZE) {
currPoint = line2[i];
break;
}
}
} else {
currPoint = null;
}
let slope1 = (line1[0].y - line1[1].y) /
(line1[0].x - line1[1].x) ;
let slope2 = (line2[0].y - line2[1].y) /
(line2[0].x - line2[1].x);
if (slope1 - slope2 != 0) {
colPoint.x = (line2[0].x * slope2 -
line1[0].x * slope1 +
line1[0].y - line2[0].y) /
(slope2 - slope1);
colPoint.y = slope1 * (colPoint.x - line1[0].x) + line1[0].y;
}
strokeWeight(2);
stroke(0);
line(line1[0].x, line1[0].y, line1[1].x, line1[1].y);
line(line2[0].x, line2[0].y, line2[1].x, line2[1].y);
strokeWeight(1);
stroke(200, 0, 0);
strokeWeight(1);
stroke(0);
fill(255, 255, 0);
circle(line1[0].x, line1[0].y, SIZE);
circle(line1[1].x, line1[1].y, SIZE);
circle(line2[0].x, line2[0].y, SIZE);
circle(line2[1].x, line2[1].y, SIZE);
circle(colPoint.x, colPoint.y, SIZE);
}