使用Browserify导出p5.js函数 [英] Exporting p5.js function with Browserify

查看:130
本文介绍了使用Browserify导出p5.js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有一个要导出的p5对象,以供browserify捆绑:

Here I have a p5 object that I am exporting to be bundled by 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对象,如下所示:

All of this works fine and I can access all built in p5 functions in other bundled scripts but not the clearCanvas function that I have defined. I also tried attaching it to the window object based on another SO post, like this:

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

到目前为止,一切都产生了Uncaught TypeError:无法设置未定义的属性'clearCanvas'

Everything so far has yielded Uncaught TypeError: Cannot set property 'clearCanvas' of undefined

知道我在做什么错吗?

推荐答案

首先,针对该部分:

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

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

To attach something to the window object do it directly,changing it to this:

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

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

Worked, however I wanted to attach to the window object as infrequently as possible. For p5.js this section in the documentation is important:

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-概述

在实例模式下运行p5.js允许我使用clearCanvas函数,而无需将其绑定到window对象.

Running p5.js in instance mode allowed me to use the clearCanvas function without binding it to the window object.

这篇关于使用Browserify导出p5.js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆