I'm planning to implement some game exemple for my pupils with p5js. I've found a strange issue. mouse events (clicks) outside the canvas are taken into account.
I understand it can be usefull. On the contrary, it can be disturbing.
Planning a small game where you can click on a figure to win, clicking on a button or a menu outside the canvas brings up a fail in the game (unintended)
An optionnal parameter ( canvasClickMode() function ?) should be used.
In p5.js, the entire browser window is considered your sketch, so a click anywhere in it triggers mousePressed() and other mouse listeners. If you'd like to only listen to the canvas, you can do something like:
function setup() {
var c = createCanvas(100, 100);
c.mousePressed(doStuff);
}
function doStuff() {
console.log('clicked on canvas');
}
I know that issue #1437 is already closed and long overdue but what worked for me was enclosing the event inside an if statement such that it would only run if (mouseX <= width && mouseX >= 0 && mouseY <= height && mouseY >= 0), that is, within the boundaries of the canvas.
Worked for me too! Thanks for this
Most helpful comment
In p5.js, the entire browser window is considered your sketch, so a click anywhere in it triggers mousePressed() and other mouse listeners. If you'd like to only listen to the canvas, you can do something like:
http://p5js.org/reference/#p5.Element/mousePressed