In basic, the p5() instance mode constructor looks something like the following:
new p5( sketch , node );
/*
sketch → Function
node → Element Node | Element ID
*/
NOTE: There's a bit more to it which I'm not covering here.
So, to make a basic one-off sketch, you could do something like the following within a passage:
!!Below you should see a basic p5js sketch.
<div id="p5sketch"></div>
<<script>>
$(document).on(':passageend', function () {
new p5(function (sketch) {
sketch.setup = function () {
sketch.createCanvas(640, 480);
sketch.background(128);
};
sketch.draw = function () {
if (sketch.mouseIsPressed) {
sketch.fill(0);
}
else {
sketch.fill(255);
}
sketch.ellipse(sketch.mouseX, sketch.mouseY, 80, 80);
};
}, 'p5sketch');
});
<</script>>
To make a sketch function which you can reuse, I'd probably suggest storing it on SugarCube's setup object, so you can refer to it whenever you'd like. For example:
setup.mySketch = function (sketch) {
sketch.setup = function () {
sketch.createCanvas(640, 480);
sketch.background(128);
};
sketch.draw = function () {
if (sketch.mouseIsPressed) {
sketch.fill(0);
}
else {
sketch.fill(255);
}
sketch.ellipse(sketch.mouseX, sketch.mouseY, 80, 80);
};
};
To use the stored setup.mySketch function within a passage:
!!Below you should see a basic p5js sketch.
<div id="p5sketch"></div>
<<script>>
$(document).on(':passageend', function () {
new p5(setup.mySketch, 'p5sketch');
});
<</script>>