Nested canvases?

Hello,

I’m new to p5.js, javascript, etc… I would like to have a canvas inside another canvas.

Here is my current code, it works but is it a bad idea ? And if so, why ?

const sketch1 = p5 => {
  p5.setup = () => {
    const canvas = p5.createCanvas(p5.windowWidth, p5.windowHeight);
    canvas.mouseOver(() => { console.log("mouse entered canvas of sketch 1"); });
    canvas.mouseOut(() => { console.log("mouse left canvas of sketch 1"); });
    p5.background("grey");
    p5.text("sketch1", 10, 20);
  };
};

const sketch2 = p5 => {
  p5.setup = () => {
    const canvas = p5.createCanvas(100, 100);
    canvas.mouseOver(() => { console.log("mouse entered canvas of sketch 2"); });
    canvas.mouseOut(() => { console.log("mouse left canvas of sketch 2"); });
    p5.background("white");
    p5.text("sketch2", 10, 20);
  };
};

const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "50%";
div.style.top = "50%";
div.style.transform = "translate(-50%, -50%)";
document.getElementsByTagName("body")[0].appendChild(div);

new p5(sketch1);
new p5(sketch2, div);

Or can it be improved? I would like to get rid of the div if possible, I think it’s an ugly hack, but again, I know nothing…

Or should I really use createGraphics instead ? How to easily replicate the mouse events then ?

Thanks :wink:

[EDIT] I’ve just realized that the mouse events can be attached to the element returned by createGraphics as well !

1 Like

I don’t think there’s a need to use a nested div. Instead, draw the second canvas/PGraphic onto the main. (Sounds like you already started looking into this :+1:)

1 Like

But how to draw/add elements inside the main canvas ? For example if I use .draw() to draw the graphics, or when add a checkbox or whatever, all goes below the canvas instead of inside the canvas as expected. I don’t understand… I tried to use .parent(canvas) but it doesn’t seem to change anything. Do I have to use ‘position’ instead, or is there a better solution ?

Could you provide the code that recreates this problem? What also would be helpful is a more detailed description of the desired behavior vs. the current behavior.

1 Like

Solved, I was thinking the Canvas was like the main window of a p5.js project, on which every elements (graphics or inputs) would be attached to. I understand now that the canvas is optional and is just like all other elements :slight_smile:

1 Like

You are recommended to have 0 or 1 canvas within a global sketch or sketch instance. And more graphics buffers (which may be shown) with createGraphics.

This method should be called only once at the start of setup. Calling createCanvas more than once in a sketch will result in very unpredictable behavior. If you want more than one drawing canvas you could use createGraphics (hidden by default but it can be shown).

You can also have multiple instance mode sketches – each with their own canvas.