使用Browserify导出p5.js函数

时间:2016-05-31 07:13:01

标签: javascript node.js browserify p5.js

这里我有一个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函数。我也尝试根据另一个SO帖子将它附加到窗口对象,如下所示:

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

到目前为止,所有东西都产生了未捕获的TypeError:无法设置未定义的属性'clearCanvas'

知道我做错了吗?

2 个答案:

答案 0 :(得分:1)

browserify构建的模块有自己的范围,因此默认情况下不会向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);
});

答案 1 :(得分:0)

首先,对于该部分:

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

要将某些内容附加到窗口对象,请直接将其更改为:

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

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

By default, all p5.js functions are in the global namespace (i.e. 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函数而不将其绑定到窗口对象。