gpt4 book ai didi

javascript - 使用 Browserify 导出 p5.js 函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:12 24 4
gpt4 key购买 nike

这里我有一个 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
}

到目前为止,一切都产生了 Uncaught TypeError: Cannot set property 'clearCanvas' of undefined

知道我做错了什么吗?

最佳答案

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

关于javascript - 使用 Browserify 导出 p5.js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37539141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com