Search code examples
pythonhtml5-canvasprocessingp5.js

Why must translate() be in draw() in p5?


Using p5 library ported to python. By default the coordinate system has 0,0 starting at the top left like HTML canvas. I'm trying to convert this to a cartesian plane with 0,0 at the center using translate() then draw a circle at 0,0 to confirm it's at the center.

It works, but only when I have translate() in def draw() instead of def setup()

This works:

from p5 import *

def setup():
    size(900, 900)

def draw():
    translate(width/2, height/2)
    circle(0, 0, 50) # draws circle at center

run()

This does not work:

from p5 import *

def setup():
    size(900, 900)
    translate(width/2, height/2)

def draw():
    circle(0, 0, 50) # draws circle at top left

run()

I've confirmed using print() statements that run() calls setup() before it calls draw(), so the translation should be happening before circle() is executed.

Why must I put translate() in draw() and not setup() if setup() is running first? Is the translation resetting every draw() execution?


Solution

  • This is actually documented here last paragraph (emphasis mine):

    It is important to note that the drawing coordinate system will be reset at the beginning of each draw() call. If any transformations are performed within draw() (ex: scale, rotate, translate), their effects will be undone at the beginning of draw(), so transformations will not accumulate over time.

    So it's not strictly Python-specific, p5.js itself specifices so and translate in setup has no effect.