I'm trying to make a p5js code that has two visual outputs:
The drawing to the offscreen buffer works fine as long as I do direct calls to p5js functions such as circle(), or rect(), but as soon as I use an object it tells me that my object is undefined.
Here is the minimal code :
let canvas;
let offscreen;
let someobject;
function setup() {
createCanvas(400, 400); // create main render view
offscreen = createGraphics(400,400); // create offscreen buffer
someobject = new SomeObject();
}
function draw() {
// do & draw things onto main render view
someobject.dothings();
someobject.drawthings();
if(true //end of simulation){
offscreen.someobject.drawthings(); // draw to offscreen buffer
offscreen.save(); // save file
noLoop(); // stop simulation
}
}
class SomeObject{
constructor(){}
doThings(){
// does things
}
drawthings(){
circle(100,100,100);
}
}
I understand the error that I get :
TypeError: offscreen.someobject is undefined
Is there a way to share the objects between the canvas and the offscreen buffer ? Or is there a more obvious solution that I'm missing ? Thanks
I've found that I can simply use the image() function of the p5js library to draw to canvas into the buffer like so :
offscreen.image(canvas,0,0)
offscreen.save(); // save file
This doesn't make sense:
offscreen.someobject.drawthings(); // draw to offscreen buffer
The p5.Graphics object offscreen does not have a someobject property and even if you had added that with offscreen.someobject = someobject; that wouldn't cause the drawing functions in someobject.drawthings() to draw to the p5.Graphics instead of the main canvas.
In order for this to work, you need to make SomeObject accept a p5 instance in its render function:
let canvas;
let offscreen;
let someobject;
function setup() {
createCanvas(400, 400); // create main render view
offscreen = createGraphics(400,400); // create offscreen buffer
someobject = new SomeObject();
}
function draw() {
// do & draw things onto main render view
someobject.dothings();
// In global mode all of the p5js drawing methods that draw to the main
// canvas are available globally, i.e. on the window object.
someobject.drawthings(window);
if(true /* end of simulation */){
someobject.drawthings(offscreen);
offscreen.save(); // save file
noLoop(); // stop simulation
}
}
class SomeObject{
constructor(){}
doThings(){
// does things
}
// This function takes an object with p5 drawing functions, such
// a p5.Graphics object
drawthings(p){
p.circle(100,100,100);
}
}