简体   繁体   中英

Creating simple p5.js canvas

I'm trying to create the most basic example of p5.js:

$(document).ready(function(){
  function setup() {
    createCanvas(500, 500);
    background(200);
  }
});

This doesn't work. Canvas was not created at all and there is no error in the console.

But this solution works:

$(document).ready(function(){
  var sketch = function(p) {
    p.setup = function () {
      p.createCanvas(640, 480);
      p.background(200);
    };
  };
  new p5(sketch);
});

I've seen it here: https://stackoverflow.com/a/41126499/2986401

However, the first example is the recommended way. Why it is not working? How can I get it at work? (I have a low level of JS) Thank you.

You should not call the setup() function yourself. The P5.js library calls it for you. Calling it yourself short-circuits all the cool stuff that P5.js does, and it's why you're getting a "createCanvas is not defined" error.

Basically, by default (aka in global mode), P5.js looks for top-level functions like setup() and draw() that it calls automatically for you after the library is loaded. That's why your first example doesn't work: the setup() function is buried inside an anonymous function that you're passing into JQuery's ready() function.

In other words, you do not want to use onload() or JQuery's ready() functions with P5.js. You want to let P5.js automatically call those functions when the library is loaded.

Here's a simple example that includes the required HTML to give you a better idea of what's going on:

<!DOCTYPE html>
<html>
    <head>
        <title>P5.js Example</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.js"></script>
        <script>
            function setup(){
                createCanvas(500, 500);
                background(64);
            }

            function draw(){
                fill(255);
                ellipse(mouseX, mouseY, 20, 20);
            }
        </script>
    </head>
    <body>
    </body>
</html>

This code defines top-level setup() and draw() functions. When the P5.js library is loaded, it automatically calls these functions.

If you try to call setup() yourself, you'll do so before P5.js is loaded, which is why the createCanvas() function is not defined.

Your second example is using instance mode , which puts the setup() and draw() function inside an object that P5.js uses for calling functions. See here for more info. But even with instance mode, you probably still wouldn't need to use the onload() or JQuery's ready() function.

Shameless self-promotion: I've written a tutorial on how P5.js works available here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM