Ad

Avoid Using Global Scope In P5

- 1 answer

I just started a new project in p5, I've already used it directly imported in the browser, but this time, since it's a more complex project, I'm going to use it in webpack.

I imported the library and bootstraped it in this way:

import * as p5 from 'p5';

function setup() {
  createCanvas(640, 480);
}

function draw() {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

But it doesn't work.

The reason is simple: webpack wraps the module in a local scope, and p5 isn't aware of it.

For this reason, I assigned the functions to the global scope:

import * as p5 from 'p5';

window.setup = function () {
  createCanvas(640, 480);
}

window.draw = function () {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

And it works fine, but still looks wrong. I don't think that pollulating the global scope is the correct way of working with JS in 2019. Expecially if I'm using webpack and I'm about to implement TypeScript.

So, how can I tell p5 to look for the functions in the module scope and not in the global one?

Ad

Answer

You'd use instance mode, which doesn't rely on globals. Here's the example from that page:

var sketch = function( p ) {

  var x = 100; 
  var y = 100;

  p.setup = function() {
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x,y,50,50);
  };
};

var myp5 = new p5(sketch);

Live Example:

var sketch = function( p ) {

  var x = 100; 
  var y = 100;

  p.setup = function() {
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x,y,50,50);
  };
};

var myp5 = new p5(sketch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>

Ad
source: stackoverflow.com
Ad