MouseOver function

Can mouseOver function detect if the mouse is on the shape drawn on the canvas. in the reference’s example, it seems it can only detect whether the mouse has entered the element, what about shapes. if it can, how to use it?

There is are statements in p5js to do this directly you have to create your own code.

Here is a simple example for you to try. The code is below.

let ball = { x: 100, y: 200, r: 50 };
let oblong = { x: 225, y: 20, w: 50, h: 260 };

function setup() {
  createCanvas(320, 320);
  cursor(CROSS);
}

function draw() {
  background(20);
  stroke(255);
  strokeWeight(3);
  if (isOverCircle(ball)) 
    fill(255, 128, 128);
  else 
    fill(64, 255, 64);
  ellipse(ball.x, ball.y, 2 * ball.r, 2 * ball.r);

  if (isOverRectangle(oblong)) 
    fill(255, 128, 128);
  else 
    fill(64, 255, 64);
  rect(oblong.x, oblong.y, oblong.w, oblong.h);
}

function isOverCircle(c, px = mouseX, py = mouseY) {
  let dx = px - c.x, dy = py - c.y;
  return dx * dx + dy * dy <= c.r * c.r;
}

function isOverRectangle(o, px = mouseX, py = mouseY) {
  let dx = px - o.x, dy = py - o.y;
  return dx >= 0 && dy >= 0 && dx < o.w && dy < o.h;
}
1 Like