我正在try 将一个草图转换为使用node并绑定一个分发js文件.我的猜测是p5js中的一些函数名必须保留(为了解决这个问题,我打算使用一个开发标志,这样至少在测试时不会混淆代码).
为了封装代码,我使用了以下方法:
let sketch = function(p) {
p.setup = function() {
...
}
let myp5 = new p5(sketch);
除了我不能在我的粒子类(ReferenceError: noStroke is not defined
)中调用show函数外,一切似乎都很好
以下是完整的js:
let canvasBG;
let particles = [];
let audioFile;
let amplitude;
let vol;
let loaded = false;
let x = 0;
let xoff = 0;
let yoff = 0;
let sketch = function(p) {
p.setup = function() {
canvasBG = p.createCanvas(p.windowWidth, p.windowHeight);
audioFile = p.loadSound("audio/mom.mp3", p.audioLoaded);
amplitude = new p5.Amplitude();
p.rectMode(p.CENTER);
p.frameRate(30);
canvasBG.background(255);
}
p.audioLoaded = function() {
audioFile.play();
audioFile.loop();
loaded = true;
}
p.draw = function() {
let nx = p.noise(xoff) * p.windowWidth;
let ny = p.noise(yoff) * p.windowHeight;
xoff = xoff + 0.01;
yoff = yoff + 0.02;
vol = amplitude.getLevel();
let volumeGate = p.map(vol, 0, 1, p.random(5,12), p.random(80, 550));
if (loaded) {
let b = new Particle(nx, ny, volumeGate);
particles.push(b);
if (volumeGate > 75) {
canvasBG.background(p.random(255), p.random(255), p.random(255));
}
for (let particle of particles) {
particle.show();
}
if (particles.length >= 10) {
particles.splice(0, 1);
}
} else {
x+= 0.05;
p.translate (p.windowWidth - 30, 30);
p.rotate(x);
p.noStroke();
p.rect(0, 0, 2, 40, 0.1);
p.fill(0, 0, 0, x * 3);
}
}
}
class Particle {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
}
show() {
noStroke(); // this is throwing an error
fill(random(0, 255), random(0, 255), random(0, 255), random(100,255));
ellipse(this.x, this.y, this.r * 2);
}
}
let myp5 = new p5(sketch);
您可以在此处运行当前的完整演示:https://editor.p5js.org/lharby/sketches/wPF908tqX
我try 将类转换为函数并传递参数,类似于一个对象,然后将函数附加到该对象,但似乎无法实现任何功能,而且我宁愿保持类的原样.
最好的方法是什么?