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
JavaScript
x
50
50
1
// Globals easily shared between sketches
2
// no P5.js methods here
3
const canvasW = 521
4
const canvasH = 322;
5
6
// Global function that doesn't work because
7
// it isn't in a p5 object??
8
// How to set this up so we can share a method
9
// across more than one sketch/canvas??
10
const draw_rect = function() {
11
rect(100, 100, 10, 10); // no context for the rect() method here
12
p55.rect(100, 100, 10, 10); // no context for p55 here unlike in the code below.
13
};
14
15
16
// Sketch 1
17
const sketch1 = (p55) => {
18
p55.setup = () => {
19
p55.createCanvas(canvasW, canvasH);
20
};
21
22
p55.draw = () => {
23
p55.background(76, 123, 199);
24
p55.fill(47, 123);
25
p55.noStroke();
26
p55.rect(p55.mouseX, p55.mouseY, 47, 47);
27
draw_rect(); // breaks
28
};
29
};
30
31
let myp5_sketch1 = new p5(sketch1, "sketch1");
32
33
34
// Sketch 2
35
const sketch2 = (p55) => {
36
p55.setup = () => {
37
p55.createCanvas(canvasW, canvasH);
38
};
39
40
p55.draw = () => {
41
// including some example drawing code
42
p55.background(76, 47, 123);
43
p55.fill(255, 199);
44
p55.noStroke();
45
p55.ellipse(p55.mouseX, p55.mouseY, 47, 47);
46
draw_rect(); // breaks
47
};
48
};
49
50
let myp5_sketch2 = new p5(sketch2, "sketch2");
JavaScript
1
23
23
1
<!DOCTYPE html>
2
<html lang="en">
3
4
<head>
5
<meta charset="utf-8" />
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
8
<title>Sketch</title>
9
10
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
11
</head>
12
13
<body>
14
<div id="sketch1">
15
<h1>Sketch1</h1>
16
</div>
17
<div id="sketch2">
18
<h1>Sketch2</h1>
19
</div>
20
<script src="sketch.js"></script>
21
</body>
22
23
</html>
Advertisement
Answer
The p5 object needs to be an argument of the function:
JavaScript
1
4
1
const draw_rect = function(p55) {
2
p55.rect(100, 100, 10, 10);
3
};
4
JavaScript
1
9
1
const sketch1 = (p55) => {
2
// [...]
3
p55.draw = () => {
4
// [...]
5
6
draw_rect(p55);
7
}
8
}
9
JavaScript
1
9
1
const sketch2 = (p55) => {
2
// [...]
3
p55.draw = () => {
4
// [...]
5
6
draw_rect(p55);
7
}
8
}
9