p5js instance mode and object orientation

1.3k views Asked by At

I have a "sketch.js" where i want to instance multiple canvases und display different objects of one class in them.

sketch.js:

var myObjects = [];

var sketch1 = function (p) {
    p.setup = function () {
        p.createCanvas(600, 400);
    }

    p.draw = function () {
        p.background(51);
        p.rect(p.width/2, p.height/2, 200, 200);
    }   
};

new p5(sketch1, "canvas_container");

var sketch2 = function (p) {
    p.setup = function () {
        p.createCanvas(600, 400);
        myObjects.push(new myObject(p, 1, 2));
        myObjects.push(new myObject(p, 3, 4));
    }

    p.draw = function () {
        p.background();
        for (var i=0; i<myObjects.length; i++) {
            p.line(0, 0, myObjects[i].x, myObjects[i].y);
            myObjects[i].doSomething(Math.random()*10);
        }
    }
};

new p5(sketch2, "canvas_container");

When do i use "this." and when "p." in this case? Furthermore I would like to use some "other" methods from the p5 library in my sketch.js file, outside of the instaces, like:

select('..') ...

but I get the error:

select is not defined

I found myself a dirt workaround:

new p5().select('...') ...

What is the clean way to do this?

myObjects.js

function myObject(canvas, x, y) {
    this.canvas = canvas;
    this.x = x;
    this.y = y;

    this.doSomething = function(rad) {
        this.canvas.ellipse(this.x, this.y, rad, rad);
    }
}

Has anybody an example for handeling multiple instances of canvases?

1

There are 1 answers

1
Kevin Workman On

Note that right now, you aren't ever creating a new instance of myObject. Your array is named myObjects, but you're only ever adding p (which is an instance of p5) to it. So you can't magically call your doSomething() function on the objects you've added to your myObjects array, because they aren't myObject objects. They're p5 objects.

I think what you would want to do is take the p variable passed into each of your sketches and pass that into your "class" functions. Something like this:

p.setup = function () {
        p.createCanvas(600, 400);
        var myObjectOne = new myObject(p, 1, 2);
        var myObjectTwo = new myObject(p, 3, 4);
}

Then it should work how you're expecting it to.