home p5.js Reference

Trigman

This is a tricky example of how to use basic mathematical functions to create complicated effects. I calculate the direction for the eyes using the difference between the mouse position and the center of the eyes. I use the distance formula to calculate how far away the irises are from the center and then use the Math.min function to keep the irises inside the bounds of the eye.

For a similar example using more powerful math techniques in a more standard and recommended way, see this example in Java (not Javascript!) from Processing.org.

let d;
let leftEyeX;
let rightEyeX;
let eyeY;

let v_lx;
let v_rx;
let v_y;
let n_lm;
let n_rm;

function setup() {
    createCanvas(600, 500);
    background(250, 230, 90);
    d = min(width, height);
    rightEyeX = width/2 + d/5;
    leftEyeX = width/2 - d/5;
    eyeY = height/2 - d/6;

    v_lx = mouseX - leftEyeX;
    v_rx = mouseX - rightEyeX;
    v_y = mouseY - eyeY;
    n_lm = Math.sqrt(v_lx^2 + v_y^2);
    n_rm = Math.sqrt(v_rx^2 + v_y^2);
}

function draw() {
    background(250, 230, 90);
    fill(255);
    circle(width/2, height/2, d);
    circle(leftEyeX, eyeY, d/5);
    circle(rightEyeX, eyeY, d/5);
    circle(width/2, height/2 + d/5, d/2)

    v_lx = mouseX - leftEyeX;
    v_rx = mouseX - rightEyeX;
    v_y = mouseY - eyeY;
    n_lm = Math.sqrt(v_lx**2 + v_y**2);
    n_rm = Math.sqrt(v_rx**2 + v_y**2);

    fill(0);
    circle(
        leftEyeX + Math.sign(v_lx) * Math.min(Math.abs(v_lx/n_lm)* d/20, Math.abs(v_lx)),
        eyeY + Math.sign(v_y) * Math.min(Math.abs(v_y/n_lm)* d/20, Math.abs(v_y)),
        d/10);
    circle(
        rightEyeX + Math.sign(v_rx) * Math.min(Math.abs(v_rx/n_rm)* d/20, Math.abs(v_rx)),
        eyeY + Math.sign(v_y) * Math.min(Math.abs(v_y/n_rm)* d/20, Math.abs(v_y)),
        d/10);

}