Target an existing canvas in the DOM instead of creating a new one

I have an HTML page with a <canvas> node already in it.

I’d like to connect a p5js sketch to it and draw in it.

I’ve seen how to target instance container (examples | p5.js) but in these example a <div> tag is targeted and a new canvas is create it it using p.createCanvas().

Is it possible to target instead an existing canvas in the HTML?

I found this page that states:

Optionally, an existing canvas can be passed using a selector, ie. document.getElementById('') . If specified, avoid using setAttributes() afterwards, as this will remove and recreate the existing canvas.

but it doesn’t provide further information. How can I pass the selection?

I checked the source code and found this

I tried passing canvas as an argument and it seems work:

1 Like