xxxxxxxxxx
112
let Ps = [];
function setup(){
createCanvas(600, 400);
}
function draw(){
background(0);
for (let i = 0; i < Ps.length; i++){
fill(255);
stroke(255);
ellipse(Ps[i].x, Ps[i].y, 5, 5);
if (Ps.length == 3){
// Draw the triangle
stroke(255);
line(Ps[0].x, Ps[0].y, Ps[1].x, Ps[1].y);
line(Ps[1].x, Ps[1].y, Ps[2].x, Ps[2].y);
line(Ps[2].x, Ps[2].y, Ps[0].x, Ps[0].y);
// Find the intersection point of 2 perpendicular lines
const circle = findCircumCircle(Ps[0], Ps[1], Ps[2]);
const c = circle.c;
const r = circle.r;
// Find the mid point of the line P1 P2
const m1 = createVector((Ps[0].x + Ps[1].x)/2, (Ps[0].y + Ps[1].y)/2);
// find the mid point of the line P2 P3
const m2 = createVector((Ps[1].x + Ps[2].x)/2, (Ps[1].y + Ps[2].y)/2);
// find the mid point of the line P3 P1
const m3 = createVector((Ps[2].x + Ps[0].x)/2, (Ps[2].y + Ps[0].y)/2);
// draw the mid points
fill(255, 0, 0);
ellipse(m1.x, m1.y, 5, 5);
ellipse(m2.x, m2.y, 5, 5);
ellipse(m3.x, m3.y, 5, 5);
// draw lines from 3 mid points to the center of the circumcircle
stroke(255, 0, 0);
line(m1.x, m1.y, c.x, c.y);
line(m2.x, m2.y, c.x, c.y);
line(m3.x, m3.y, c.x, c.y);
// draw the center of the circumcircle
fill(0, 255, 0);
ellipse(c.x, c.y, 6, 6);
// draw the circumcircle
noFill();
stroke(0, 255, 0);
ellipse(c.x, c.y, r*2, r*2);
}
}
}
// find the circumcircle of 3 points
function findCircumCircle(p1, p2, p3){
const len = 200;
// find the mid point of the line P1 P2
const m1 = createVector((p1.x + p2.x)/2, (p1.y + p2.y)/2);
let [h1, h2] = perpendicularOfALine(p1, p2);
// find the mid point of the line P2 P3
const m2 = createVector((p2.x + p3.x)/2, (p2.y + p3.y)/2);
let [h3, h4] = perpendicularOfALine(p2, p3);
// find the intersection point of 2 perpendicular lines
const c = findIntersectionOfTwoLines(m1, createVector(m1.x + h1.x * len, m1.y + h1.y*len), m2, createVector(m2.x + h3.x * len, m2.y + h3.y*len));
// find the radius of the circumcircle
const r = dist(c.x, c.y, p1.x, p1.y);
return {c, r};
}
// find a perpendicular line at point M with line P1 P2
function perpendicularOfALine(p1, p2){
// find perpendicular vector of P1 P2
const v = createVector(p2.x - p1.x, p2.y - p1.y).normalize();
const pVector1 = createVector(v.y, -v.x);
const pVector2 = createVector(-v.y, v.x);
return [pVector1, pVector2];
}
// findIntersectionOfTwoLines
function findIntersectionOfTwoLines(p1, p2, q1, q2){
const a1 = p2.y - p1.y;
const b1 = p1.x - p2.x;
const c1 = a1 * p1.x + b1 * p1.y;
const a2 = q2.y - q1.y;
const b2 = q1.x - q2.x;
const c2 = a2 * q1.x + b2 * q1.y;
const det = a1 * b2 - a2 * b1;
if (det == 0){
return createVector(0, 0);
} else {
const x = (b2 * c1 - b1 * c2) / det;
const y = (a1 * c2 - a2 * c1) / det;
return createVector(x, y);
}
}
function mousePressed(){
if (Ps.length == 3){
Ps = [];
}
Ps.push(createVector(mouseX, mouseY));
}