Avoid using global scope in p5

问题: 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 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?


回答1:

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>

  • 发表于 2019-02-18 04:10
  • 阅读 ( 179 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除