Exporting a function from p5.js with Browserify
<p>First, I have a p5.js script:</p>

<pre><code>//canvas.js
var p5 = require('p5')

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')
  }
</code></pre>

<p>Everything is in a new p5 object so that it would bundle with browserify because p5, as I understand runs in the global namespace. This worked fine but I needed a button that would turn the whole canvas black so I added a new function clearCanvas that redraws the canvas all in black. I added the module.exports part so that I could require in the p5 object and use this new function in another script. Then I added a button in my jade file:</p>

<pre><code>    button(type='button', id='clear').
            Click to clear
</code></pre>

<p>And then I created a handler that would require in the p5 exported object and use the clearCanvas function onClick:</p>

<pre><code>var canvas = require('./canvas.js')

document.getElementById('clear').onclick = function () {
  canvas.clearCanvas()
}
</code></pre>

<p>The result is two errors in the console:</p>

<p>bundle.js:34633 Uncaught TypeError: Cannot set property 'onclick' of null</p>

<p>bundle.js:14197 p5 had problems creating the global function "clear", possibly because your code is already using that name as a variable. You may want to rename your variable to something else.</p>