2016-05-31 56 views
2

在這裏,我有我出口由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

回答

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

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