Hiya,
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:
myGraphics.myFunction();
...
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:
https://editor.p5js.org/hapiel/sketches/F1WHueh48
And also pasted here:
let layerDraw;
function setup() {
createCanvas(400, 400);
layerDraw = createGraphics(width, height);
}
function draw() {
background(123);
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;
push()
translate(x, y);
beginShape();
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);
}
}
endShape(CLOSE);
pop();
}
Thanks for taking a look!