How can I share methods that call P5.js functions between two different sketches/canvases?

Tags: , ,



Is there a way to share common methods between two different sketches/canvases? It only works if I’m not referencing any P5.js methods.

In the example below there are two sketches and each is loaded into a different canvas element using the instance mode for P5.js.

I’d like to be able to write a function that uses P5.js methods AND is accessible to each sketch.

Basically I’m trying to avoid duplicating code in two sketches if it isn’t necessary.

Thanks

// Globals easily shared between sketches
// no P5.js methods here
const canvasW = 521
const canvasH = 322;

// Global function that doesn't work because 
// it isn't in a p5 object?? 
// How to set this up so we can share a method 
// across more than one sketch/canvas??
const draw_rect = function() {
  rect(100, 100, 10, 10); // no context for the rect() method here
  p55.rect(100, 100, 10, 10); // no context for p55 here unlike in the code below.
};


// Sketch 1
const sketch1 = (p55) => {
  p55.setup = () => {
    p55.createCanvas(canvasW, canvasH);
  };

  p55.draw = () => {
    p55.background(76, 123, 199);
    p55.fill(47, 123);
    p55.noStroke();
    p55.rect(p55.mouseX, p55.mouseY, 47, 47);
    draw_rect(); // breaks
  };
};

let myp5_sketch1 = new p5(sketch1, "sketch1");


// Sketch 2
const sketch2 = (p55) => {
  p55.setup = () => {
    p55.createCanvas(canvasW, canvasH);
  };

  p55.draw = () => {
    // including some example drawing code
    p55.background(76, 47, 123);
    p55.fill(255, 199);
    p55.noStroke();
    p55.ellipse(p55.mouseX, p55.mouseY, 47, 47);
    draw_rect(); // breaks
  };
};

let myp5_sketch2 = new p5(sketch2, "sketch2");
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Sketch</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
</head>

<body>
  <div id="sketch1">
    <h1>Sketch1</h1>
  </div>
  <div id="sketch2">
    <h1>Sketch2</h1>
  </div>
  <script src="sketch.js"></script>
</body>

</html>

Answer

The p5 object needs to be an argument of the function:

const draw_rect = function(p55) {
    p55.rect(100, 100, 10, 10);
};
const sketch1 = (p55) => {
    // [...]
    p55.draw = () => {
        // [...]
       
        draw_rect(p55);
    }
}
const sketch2 = (p55) => {
    // [...]
    p55.draw = () => {
        // [...]
       
        draw_rect(p55);
    }
}


Source: stackoverflow