导出p5.js与Browserify功能

问题描述:

在这里,我有我出口由browserify捆绑一个P5对象:导出p5.js与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函数。我也试图将其连接到基于另一个窗口对象,以便张贴,像这样:

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

一切至今已取得遗漏的类型错误:无法设置属性“clearCanvas”未定义

任何想法是什么我”米做错了吗?

+0

我刚刚检查了[p5.js on github]的代码(https://github.com/processing/p5.js/search?utf8=%E2%9C%93&q=clearCanvas),似乎有没有'clearCanvas'功能。它在哪里提到?我还检查了文档:'createCanvas()','resizeCanvas()','noCanvas()','createGraphics()','blendMode()'是它所提供的。 –

+0

clearCanvas是我定义的使用redraw()函数的函数。我没有问题从其他捆绑脚本访问内置于p5的函数,但是如果我在canvas.js(上面的脚本)中创建函数并捆绑它。我可以在另一个脚本中访问我在canvas.js中创建的函数,还是只能使用内置于p5.js中的函数? – Nohman

首先,对于部分:

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功能不绑定到window对象。

由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); 
});