Choky
1
When creating a class I cannot make it so the class gets all the functions of p5.js library.
Can anyone help me?
it says fill is not defined
code :
var game = function(g) {
g.setup = function() {
g.createCanvas(400,400);
g.background(0);
g.snake = new Snake();
g.snake.test();
}
}
class Snake {
test() {
fill(255); //this line throws error (Uncaught ReferenceError: fill is not defined)
ellipse(0,0,100); }
}
var mySnake = new p5(game);
It doesn’t seem you’re trying to expand p5js’ API, but rather you wanna access its API from inside your class, right?
If you’re using the instance mode style approach:
Your classes are gonna need to request the current sketch’s p5 reference in their constructor, something like this:
class Snake {
constructor(p) {
this.p = p || p5.instance;
}
display() {
const { p } = this;
p.fill(0xff).circle(p.width - 50 >> 1, p.height - 50 >> 1, 100);
return this;
}
}
new p5(p => {
let snake;
p.setup = () => {
p.createCanvas(400, 400);
snake = new Snake(p);
};
p.draw = () => {
p.background(0);
snake.display();
};
});
Here’s a more complete online sketch to show you better how it works: