使用Browserify导出p5.jsfunction

在这里,我有一个p5对象,我将导出为由browserify捆绑在一起:

var p5 = require('p5') var colorPicker = require('./color_picker.js') module.exports = new p5(function () { this.setup = function setup () { this.createCanvas(700, 400) this.background(205) this.loadImage('/uploads/uploaded_image', function (img) { image(img, 0, 0) }) this.updatePixels() } this.clearCanvas = function redraw () { this.background('black') } this.mouseDragged = function mouseDragged () { var rgb = colorPicker.getRGB() this.stroke(rgb.r, rgb.g, rgb.b) this.strokeWeight(10) this.line(this.pmouseX, this.pmouseY, this.mouseX, this.mouseY) } }) 

所有这些工作正常,我可以访问其他捆绑脚本中的所有内置p5函数,但不是我定义的clearCanvas函数。 我也尝试将它附加到基于另一个SOpost的窗口对象,如下所示:

 window.this.clearCanvas = function redraw(){ //code } 

到目前为止,所有的东西都产生了Uncaught TypeError:不能设置属性'clearCanvas'的undefined

任何想法我做错了什么?

由browserify构build的模块有自己的范围,因此默认情况下, window对象没有任何内容。 您明确地需要将您的东西附加到window对象以从浏览器访问它。

 var p5 = require('p5') var colorPicker = require('./color_picker.js') module.exports = new p5(function () { // ... this.clearCanvas = function redraw () { this.background('black') } // ... window.clearCanvas = this.clearCanvas.bind(this); }); 

首先,对于该部分:

 window.this.clearCanvas = function redraw(){ //code } 

附加一些东西到窗口对象直接做,将其更改为:

 window.clearCanvas = function redraw(){ //code } 

工作,但是我想附加到窗口对象尽可能不经常。 对于p5.js,文档中的这一部分很重要:

 By default, all p5.js functions are in the global namespace (ie bound to the window object), meaning you can call them simply ellipse(), fill(), etc. However, this might be inconvenient if you are mixing with other JS libraries or writing long programs of your own. To solve this problem, there is something we call "instance mode", where all p5 functions are bound up in a single variable instead of polluting your global namespace. 

https://github.com/processing/p5.js/wiki/p5.js-overview

在实例模式下运行p5.js允许我使用clearCanvas函数,而不绑定到窗口对象。

Interesting Posts