Instance mode events affecting entire html

I am having an issue where the events associated with p are being applied to the entire HTML document. If I am clicking on or off the canvas, the event will be fired. Returning false also prevents default for the entire document, where you would expect to only prevent default events on the canvas element itself. Everything is being drawn appropriately.

Using the browser inspector tool I can see that the mousePressed functionality has been applied to the canvas but the entire html document has listeners from P5js. Is there a way to stop this application to the entire html, or at least make P5js only fire events on the canvas.

Below is a simplified implementation:


var s = function( p ) {
 
    
  p.setup = function() {
  
    p.createCanvas(300, 300);
  };

  p.draw = function() {
  	p.background(0);
    p.rect(20,100,50,50);
  };

  p.mousePressed = function () {
      console.log(p.mouseX);
      // return false; to prevent default
}
 
};

var myp5 = new p5(s, "container");

1 Like

https://p5js.org/reference/#/p5.Element/mousePressed

2 Likes

For the purpose of clarity: the solution is to implement the P5 instance within an iframe which can then be “included/embedded” in a larger document; hence only affecting the iframe event listeners.

Thank you and apologies for such an obvious answer.

Although an <iframe> can definitely isolate a sketch and its listeners from the rest, what I actually meant as answer was using the p5.Element::mousePressed() in place of p5::mousePressed():

  1. reference | p5.js
  2. reference | p5.js

While p5::mousePressed() listens to the whole browser’s window, p5.Element::mousePressed() listens to the element only, regardless the sketch is in global or instance mode.

Here’s another sketch in instance mode whose mousePressed() only triggers inside its canvas:
https://GoSubRoutine.GitHub.io/Ball-in-the-Chamber/p5js-instance/
https://github.com/GoSubRoutine/Ball-in-the-Chamber/blob/v3.0.0/p5js-instance/sketch/sketch.js#L24-L25

2 Likes