Isky Mathews
Isky Mathews

Reputation: 250

Using Processing PGraphics in Python Mode?

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?

Upvotes: 0

Views: 305

Answers (1)

George Profenza
George Profenza

Reputation: 51837

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()

PGraphics in PythonMode

Upvotes: 0

Related Questions