xxxxxxxxxx
79
let eyes = []; // array to store multiple "Eye" objects
let gridSize = 5; // grid size (5x5)
function setup() {
createCanvas(500, 500);
background("#FF2E3F");
angleMode(DEGREES);
// create a 5x5 grid of "Eye" objects
let spacing = width / gridSize;
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
let x = spacing / 2 + i * spacing;
let y = spacing / 2 + j * spacing;
eyes.push(new Eye(x, y, 65, 40, 20));
}
}
}
function draw() {
background("#FF2E3F");
noStroke();
// loop through the array of Eye objects and draw each one
for (let eye of eyes) {
eye.display(); // call display method for each Eye object
}
}
// eye class to manage individual eyes
class Eye {
constructor(x, y, eyeSize, irisSize, pupilSize) {
this.x = x;
this.y = y;
this.eyeSize = eyeSize;
this.irisSize = irisSize;
this.pupilSize = pupilSize;
}
display() {
// draw the sclera (white part)
fill("#F2F2F2");
ellipse(this.x, this.y, this.eyeSize, this.eyeSize);
// calculate the angle between mouse and the eye center
let angle = atan2(mouseY - this.y, mouseX - this.x);
// calculate the maximum distance the iris/pupil can move
let maxDist = (this.eyeSize / 2) - (this.pupilSize / 2);
let distanceFromCenter = dist(mouseX, mouseY, this.x, this.y);
// constrain the movement distance
let moveDist = min(distanceFromCenter, maxDist);
// calculate the new iris and pupil positions
let irisX = this.x + cos(angle) * moveDist;
let irisY = this.y + sin(angle) * moveDist;
// determine stretch factor near the edge
let edgeThreshold = (this.eyeSize / 2) - this.irisSize;
let stretch = distanceFromCenter >= edgeThreshold
? map(distanceFromCenter, edgeThreshold, this.eyeSize / 2, 1, 0.5)
: 1;
stretch = constrain(stretch, 0.5, 1);
// draw the iris
push();
translate(irisX, irisY);
rotate(angle);
fill("#275AF2");
ellipse(0, 0, this.irisSize * stretch, this.irisSize);
// draw the pupil
fill(0);
ellipse(0, 0, this.pupilSize * stretch, this.pupilSize);
pop();
}
}