本文介绍了在实例模式下使用p5.sound.js:"p5.Amplitude()不是构造函数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用npm,webpack,babel环境编写带有p5.js的应用程序.为了能够将草图作为模块,我在实例模式并将库和附加组件作为模块导入:

I am using an npm, webpack, babel environment to write an application with p5.js. To be able to have the sketch as a module, I have the sketch in instance mode and import the library and add-ons as modules:

import p5 from 'p5';
import 'p5/lib/addons/p5.sound';
import 'p5/lib/addons/p5.dom';

然后将它们加载到草图中的窗口中:

Then I load them to the window inside my sketch:

const sketch = (p5) => {
   window.p5 = p5;
   ...
}
new p5(sketch);

当我尝试使用时:

amp = new p5.Amplitude()

我收到"p5.Amplitude不是构造函数"错误.我的预测是,在窗口上命名库p5与使用库中使用p5的构造函数(例如p5.Amplitude,p5.Vector,p5.Soundfile)之间存在冲突.我还没有找到在实例模式下使用这些对象或构造函数的解决方法.但是,我可以使用这些对象中不需要构造函数的方法.例如,loadSound()是p5.Soundfile的方法.以下作品:

I get a 'p5.Amplitude is not a constructor' error. My prediction is that there is a conflict between naming the library p5 on the window and using the constructors from the library that use p5.something like p5.Amplitude, p5.Vector, p5.Soundfile. I have not been able to find a workaround to using these objects or constructors within instance mode. I am however able to use the methods from these objects that do not require a constructor. For example, loadSound() is a method of p5.Soundfile. The following works:

sound = p5.loadSound('assets/sound.wav)

但是当我尝试console.log(p5.SoundFile)时,我变得不确定.

but when I try console.log(p5.SoundFile) I get undefined.

我迷路了!

推荐答案

我不是JavaScript专家,但是您的语法与实例模式页面.

I'm not a JavaScript expert, but your syntax doesn't match the syntax on the instance mode page.

具体地说,你在这里做什么?

Specifically, what are you doing here?

const sketch = (p5) => {
   window.p5 = p5;
   ...
}
new p5(sketch);

将其与实例模式页面上的语法进行比较:

Compare that to the syntax on the instance mode page:

var sketch = function (p) {
  var gray = 0;

  p.setup = function () {
    p.createCanvas(600, 400);
  };

  p.draw = function () {
    p.background(gray);
    p.rect(p.width/2, p.height/2, 200, 200);
  };

  p.mousePressed = function () {
    gray = (gray + 16) % 256;
  };
};

new p5(sketch);

看起来您的代码正在重新定义p5变量,这将导致您遇到的各种问题.我将重写您的代码以不再重新定义p5变量,而改用实例模式页面中的语法:

It looks like your code is redefining the p5 variable, which is going to cause the kinds of problems you're seeing. I would rewrite your code to no longer redefine the p5 variable, and use the syntax from the instance mode page instead:

var sketch = function(p) {
   //your code here
   //but don't change the p5 variable!
}
new p5(sketch);

这篇关于在实例模式下使用p5.sound.js:"p5.Amplitude()不是构造函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:22