简体   繁体   English

p5.js 实例模式下的依赖,不传递实例

[英]Dependency in p5.js instance mode without passing the instance

From what I've gathered, using global mode in p5 is discouraged because it pollutes the global namespace.根据我收集到的信息,不鼓励在 p5 中使用全局模式,因为它会污染全局命名空间。 I have used instance mode for a while, but creating dependencies is always frustrating.我使用实例模式已经有一段时间了,但是创建依赖项总是令人沮丧。 In order to use p5 functions, all of my functions in other files have to have the whole p5 instance passed into them.为了使用 p5 函数,我在其他文件中的所有函数都必须将整个 p5 实例传递给它们。 If I'm creating a bunch of entities in a project, I'm wasting a whole bunch of resources by having each of them contain the whole p5 library essentially.如果我在一个项目中创建一堆实体,那么我会浪费一大堆资源,因为它们每个都包含整个 p5 库。 Is there any better way to approach this?有没有更好的方法来解决这个问题?

In my understanding, you don't have to "pass" the p5 instance into your functions in other files.据我了解,您不必将 p5 实例“传递”到其他文件中的函数中。 The p5 instance should be declared global. p5 实例应该被声明为全局的。 This should not use more resources than in the global mode case.这不应该比全局模式使用更多的资源。

So rather than having all the p5 functions attached to the global window object (the global mode), now we have all of them attached to the global p5 instance object (the instance mode).因此,与其将所有 p5 函数附加到全局window object(全局模式),现在我们将它们全部附加到全局 p5 实例 object(实例模式)。 It's just a matter of namespace.这只是命名空间的问题。

Consider the example below, which is a modified version of an example on p5 website :考虑下面的示例,它是p5 网站上示例的修改版本:

//sketch.js
let sketch = function(p) {
  let x = 100;
  let y = 100;

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

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

var myp5 = new p5(sketch);

And you can manipulate the global myp5 instance in other files.您可以在其他文件中操作全局myp5实例。 For example, in your other.js :例如,在您的other.js中:

//other.js
function randomBackgroundColor() {
  myp5.background(myp5.random(0, 255));
}

setInterval(randomBackgroundColor, 1000); //change background color every 1000 milliseconds

Including these two js files (with sketch.js first) in your html file results in a canvas with a changing background and a rectangle.在 html 文件中包含这两个 js 文件(首先是 sketch.js)会导致 canvas 具有不断变化的背景和一个矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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