Using Processing PGraphics in Python Mode?

試著忘記壹切 提交于 2021-02-05 11:42:35

问题


In Processing's Java Mode, you use PGraphics objects by declaring them globally, setting them up with createGraphics() in setup() and then referring to them in draw().

In the Python mode, what to do is not so clear and doesn't seem to be explained by the documentation. You can't declare variables in Python and variables are not automatically global, i.e. if I just say in setup() c = createGraphics(400,400) and then in draw() say c.beginDraw() I get a NameError: global name 'c' is not defined and this can't simply be fixed by saying global c in the line above.

So how is it done?


回答1:


It can be fixed using global. Be sure to use global where you initialise the canvas too, otherwise it's a local variable and your global canvas reference may still be None

Here's a basic example:

# global reference
canvas = None

def setup():
    size(300, 300)
    # setup global canvas
    global canvas
    canvas = createGraphics(300, 300)

    canvas.beginDraw()
    canvas.background(0);
    canvas.noStroke()
    canvas.blendMode(DIFFERENCE)
    canvas.ellipse(150,150,150,150)
    canvas.endDraw()

def draw():
    # reference global canvas to draw
    global canvas
    image(canvas,0,0)

def mouseDragged():
    diameter = dist(mouseX,mouseY,pmouseX,pmouseY)
    # reference global canvas to update graphics
    global canvas
    canvas.beginDraw()
    canvas.ellipse(mouseX,mouseY,diameter,diameter)
    canvas.endDraw()



来源:https://stackoverflow.com/questions/61139974/using-processing-pgraphics-in-python-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!