xxxxxxxxxx
101
// Positions for 3 points
let x1, y1, x2, y2, x3, y3;
// Position for mid-point between 3 points
let avgX, avgY;
// Diagonal of canvas
let diag;
// Which mode
let mode = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
// Start out on a diagonal
x1 = width * 0.25;
y1 = height * 0.25;
x2 = width * 0.75;
y2 = height * 0.67;
x3 = width / 2;
y3 = height / 2;
diag = sqrt(sq(width), sq(height));
rectMode(CENTER);
noStroke();
}
function draw() {
background(0);
// Find the avgX, avgY
avgX = (x1 + x2 + x3) / 3;
avgY = (y1 + y2 + y3) / 3;
// Draw a boundary around the furthest point
let d1 = dist(avgX, avgY, x1, y1);
let d2 = dist(avgX, avgY, x2, y2);
let d3 = dist(avgX, avgY, x3, y3);
// Sort distances
let ds = [d1, d2, d3];
ds.sort(function(a, b) {
return a - b;
});
// Use the shortest distance as the length of a side of the square
let s = ds[mode] * 2;
// Draw the rect (a square)
fill('white');
rect(avgX, avgY, s, s);
fill('red');
// Draw the positions
ellipse(x1, y1, 10, 10);
ellipse(x2, y2, 10, 10);
ellipse(x3, y3, 10, 10);
// Draw the average point
//ellipse(avgX, avgY, 20, 20);
}
// Move the point closest to the mouse with the mouse
// if mouse is being dragged
function mouseDragged() {
// Calculate distances of points from mouse
let d1 = dist(mouseX, mouseY, x1, y1);
let d2 = dist(mouseX, mouseY, x2, y2);
let d3 = dist(mouseX, mouseY, x3, y3);
// Store the distances in an array
// Find the shortest distance
// Record index number of shortest distance
let ds = [d1, d2, d3];
let low = diag;
let lowIndex = -1;
for (let d = 0; d < ds.length; d++) {
if (ds[d] < low) {
low = ds[d];
lowIndex = d;
}
}
// Set the position closest to mouse
// to the mouse position
if (lowIndex == 0) {
x1 = mouseX;
y1 = mouseY;
} else if (lowIndex == 1) {
x2 = mouseX;
y2 = mouseY;
} else {
x3 = mouseX;
y3 = mouseY;
}
}
function keyPressed() {
mode++;
mode %= 3;
console.log(mode);
}