Adding event handlers to sketch

Hi I’m trying to create a library that extends p5. I want to add event handlers to the sketch. I tried to use _onmousedown event present in p5 prototype, but its giving me an errror. How can I achieve this?

I could just attach an event listener to document. But is there a more elegant way of doing this?

1 Like
  • I believe you meant the sketch’s main canvas, right?
  • You can access the main canvas via the hidden/undocumented/private properties p5::_renderer or p5::_curElement.
  • From there, given it’s of datatype p5.Renderer: reference | p5.js
  • You can invoke its parent datatype p5.Element’s methods: reference | p5.js
  • Such as p5.Element::mousePressed(): reference | p5.js
  • Or alternatively via property p5.Element::elt: reference | p5.js
3 Likes

One more doubt, Does mousePressed support multiple event handlers? I.e Can we call mousePressed multiple times to attach multiple call back functions?

It seems indeed if we call method p5::mousePressed() multiple times it would replace its previous callback w/ the current 1.

If you need a p5.Element to have multiple callbacks for the same event you’re gonna need to call method EventTarget::addEventListener() over its property p5.Element::elt:

1 Like