How to get instance p5 object when clicking on the div container?

Hello all !
How to get instance p5 object when clicked on the div which contain this p5 instance canvas ?
Actually, I have an array of array {divName,p5Inst} divname + P5 object. When I clic on the div, then I can get the P5 object. but I would like to know if it’s necessary to acces to P5 instance.
Maybe I can find it from an other way without my array of array ?.
exemple here : p5.js Web Editor
Thanks for your help.

Hi @Chris,

Short answer would be no, as the p5 object in not part of the underlying div, resp. canvas.
The p5 object only have references to the div/drawing canvas and uses it.

But you can refactor your code in that way that it is bit more OO, so the single resizable divs are represented by its own class object which has its own p5 object and div on which the operations are done.

Cheers
— mnse

So you have a webpage with multiple sketches and you want to know which should process the documents mouse events.

The simplest way would be for each sketch to process the mouse events ONLY IF the mouse is over its own canvas.

The sketch below shows a one way to do it and should be extendable to suit your purpose

let mySketch = function (p) {
    mouseOverCanvas = false;
    backCol = 128;
    div_name = 'sketch'; // Make sure you have a div with this ID

    p.setup = function () {
        let p5canvas = p.createCanvas(300, 200);
        p5canvas.parent(div_name); // Add to HTML element with the given ID 
        // Add event handlers for this sketch
        p5canvas.canvas.addEventListener('mouseenter', (e) => { mouseOverCanvas = true; });
        p5canvas.canvas.addEventListener('mouseout', (e) => { mouseOverCanvas = false; });
        p.x = p.width/2;
        p.y = p.height/2;
    }

    p.draw = function () {
        p.background(backCol);
        p.fill(255,0,0);
        p.noStroke();
        p.ellipse(p.x,p.y,20,20);
    }

    p.mouseClicked = function(){
        if(mouseOverCanvas){
            p.x = p.mouseX;
            p.y = p.mouseY;
        }
    }

    p.mouseDragged = function () {
        if (mouseOverCanvas)
            backCol = p.floor(p.random(256));
    }

}

new p5(mySketch);
3 Likes

Thank you mnse.
You’r right more OO is better…
I have to optimize all. And your suggestion is intresting.
best regards.
Chris

Thank you @quark
your solution is very good I think. to put all interactions inside the P5 object.
Moreover, it will make the code safer.
I will work in this way.
Best regards.
Chris