Drawing with custom function on p5.Graphics layer


I wrote a function which draws a shape for me, and now I want to draw that shape onto a p5.Graphics layer. How do I do that?
Normally I write myGraphics.ellipse(0,0,10); which works fine, but I can’t write:

function myFunction() { ellipse(0,0,10);

Can I somehow enter the p5.Graphics object as a parameter? Or is there another way to do this? Or was it a silly idea to draw a shape with a function to begin with?

My full code in action, I hope that makes it a bit more clear what I’m trying to do:


And also pasted here:

let layerDraw;

function setup() {
  createCanvas(400, 400);

  layerDraw = createGraphics(width, height);


function draw() {


  ngon(mouseX, mouseY, 5, 50);

  if (mouseIsPressed) {

    //I want to write this shape onto layerDraw
    ngon(mouseX, mouseY, 5, 50); 
    //like I write this line to layerdraw:
    layerDraw.line(mouseX, mouseY, pmouseX, pmouseY);

  image(layerDraw, 0, 0);


function ngon(x, y, sides, sz, star = false, ins_ = sz/2, midPos = 0.5){
  //simple multigon ngon or star drawing, starting on the right.
  //x, y, amount of sides, size (diameter if it were in a circle)
  //optional: star (true/false), star depth radius, position of middle (default 0.5. 0 or 1 is under the points.)

  let angle = TWO_PI / sides;
  let r = sz/2;
  let inside = ins_/2;

  translate(x, y);
  for (let i = 0; i < sides; i++) {
    x = r * cos(angle * i);
    y = r * sin(angle * i);
    vertex(x, y);   
    if (star){
      x = inside * cos(angle * i + angle*midPos);
      y = inside * sin(angle * i + angle*midPos);
      vertex(x, y);   

Thanks for taking a look!

1 Like

You can request the layer canvas as an extra argument for your ngon() function:
function ngon(x, y, sides, sz, star = false, ins_ = sz/2, midPos = .5, pg = p5.instance) {

Now prefix all drawing-related methods w/ that pg parameter:

  • push(); -> pg.push();
  • beginShape(); -> pg.beginShape();
  • vertex(x, y); -> pg.vertex(x, y);

That’s exactly what I needed!

I do wonder: I can’t find anything about p5.instance in the p5 reference. How could I have been able to work out that this is the default graphics object?

It’s undocumented for internal use I guess. :see_no_evil:

Actually it’s the sketch’s global p5 reference. But its methods act upon the main canvas too. :paintbrush:

1 Like