0

I've been using Stackblitz as my IDE to enable me to code better on my Chromebook, it does work well but I have been struggling to implement the p5 library. I should mention that I have only recently picked up programming so I'll only understand the absolute basics.

I've added the p5 dependency and later the p5.js file whilst linking it in the HTML. And still nothing.

If all was working the draw function would call itself on a loop and draw the requested background and square. If I try to call the function as one would normally do in JavaScript it will give me the error: "background is not defined" essentially telling me that p5 is not implemented.

Deohgu
  • 55
  • 1
  • 8

1 Answers1

0

Since the p5 dependency is injected and managed with npm, you'll need to use the p5.js instance mode. In order to run in StackBlitz, after you inject the p5 dependency, your code should look similar to this:

import p5 from 'p5';

let sketch = (p) => {

  p.setup = () => {
    p.createCanvas(500, 500);
  };

  p.draw = () => {
    p.background(220);
    p.fill(120);
    p.rect(50, 50, 100, 100);
    console.log("Hello? 1")
  };

  console.log("Hello? 2")
};

let myp5 = new p5(sketch);

Keep in mind that when you want to use a p5 function, while in instance mode, you need to call it as a method of the p (or whichever name you want to give it) object but native JS methods can be called normally.

Julian
  • 1,277
  • 1
  • 9
  • 20
  • Also, the p5 file in your root directory is not needed and the IDE might not like it and get fussy about it. – Julian Feb 10 '19 at 18:06