P5 Python: How to get mouse position

Date: 2020-01-21 | python | p5 | p5py |

problem

I'm using p5py - the Python port of the P5 library from Processing - to create some sketches in my journey through The Nature of Code. I want to use the mouse position as input.

solution

Within your draw function, you can access the mouse's x and y position via the mouse_x and mouse_y variables. These are automagically set behind the scenes within the p5 framework, so all you have to do is read the values.

Here's an example p5py sketch that draws circles at the position of the mouse in every run of draw:

from p5 import *

def setup():
    size(640, 360)
    stroke(Color("#be403b"))
    background(204)

def draw():

    circle((mouse_x, mouse_y), 1)

def key_pressed(event):
    background(204)

run()

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.