Skip to main content

p5-python

p5-python brings the friendly p5.js drawing API to Python. It is a free and open-source library built by an inclusive, nurturing community and welcomes artists, designers, beginners, educators, and anyone else.

Sketches are written with familiar p5 conventions (setup, draw, createCanvas, background, fill, ...) and rendered with pygame and Cairo.

Installation

pip install p5-python

Requirements: Python 3.8+, pygame >= 2.1.2, pycairo >= 1.20.0.

Quick start

Create sketch.py:

from p5 import *


def setup():
    createCanvas(640, 360)


def draw():
    background(20)
    fill(255, 120, 40)
    noStroke()
    circle(mouseX, mouseY, 60)


run()

Run it either directly or through the module runner:

python sketch.py
python -m p5 sketch.py

What is supported

Canvas and program flow

createCanvas, resizeCanvas, saveCanvas, saveFrame, background, clear, run, stop, frameRate, getFrameRate, loop, noLoop, redraw, isLooping, cursor, noCursor, pixelDensity, smooth, noSmooth, angleMode.

Angles are measured in radians by default, matching p5.js. Call angleMode(DEGREES) if you prefer degrees.

Shapes

point, line, rect, square, ellipse, circle, arc, triangle, quad, bezier, curve, plus the vertex API:

beginShape()
vertex(100, 100)
vertex(200, 40)
vertex(300, 100)
endShape(CLOSE)

beginShape() accepts POINTS, LINES, LINE_STRIP, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN, QUADS, and QUAD_STRIP. Vertices can be mixed with curveVertex() and bezierVertex(); endShape(CLOSE) closes and fills the outline.

Drawing modes: rectMode, ellipseMode, imageMode (CORNER, CORNERS, CENTER, RADIUS).

Colour

fill, stroke, noFill, noStroke, color, colorMode, lerpColor, and the channel accessors red, green, blue, alpha, hue, saturation, brightness, lightness.

colorMode() supports RGB and HSB with custom ranges, plus an optional alpha range.

Typography

text, textFont, textSize, textStyle, textAlign, textWidth, textLeading, textWrap, loadFont.

Images and pixels

loadImage, image, PImage, createImage, tint, noTint, loadPixels, updatePixels, get, set, blendMode. get()/set() work on both the whole canvas and rectangular regions, and pixels is exposed as a writable RGBA list. saveCanvas and saveFrame write PNG files (with a JPG fallback).

PImage objects can be created in memory, edited pixel by pixel, and drawn:

img = createImage(64, 64)
img.loadPixels()
for i in range(0, len(img.pixels), 4):
    img.pixels[i:i + 4] = [255, 128, 0, 255]
img.updatePixels()

tint(255, 150)
image(img, 20, 20)
noTint()

screen.pixels is an alias for the global pixels array, and println(...)/print(...) write to standard output.

Math and randomness

abs, ceil, floor, round, sq, sqrt, pow, exp, log, log2, log10, logb, sin, cos, tan, asin, acos, atan, atan2, degrees, radians, dist, mag, map, norm, lerp, constrain, sign, min, max, random, randomSeed, randomGaussian, noise, noiseSeed, noiseDetail, shuffle, nf.

Transforms

push, pop, translate, rotate, scale, shearX, shearY, applyMatrix, resetMatrix. Transforms use a real affine matrix, so they compose and nest correctly.

Vectors

v = createVector(3, 4)
v.add(createVector(1, 2))
print(v.mag())       # 6.324...
print(v.heading())

Vector (also available as PVector) supports add, sub, mult, div, mag, magSq, normalize, limit, heading, rotate, lerp, dist, dot, cross, copy, get, set, setMag, and the usual operators.

Compatibility helpers

For sketches written in a Processing style the following are also available:

  • environment (frameCount, width, height, focused, ...)
  • keyboard (key, keyCode, keyIsPressed, keys)
  • mouse (x, y, px, py, pressed, button, ...)
  • focused
  • textAscent(), textDescent()
  • WEBGL mode renders real 3D geometry with PyOpenGL: box, sphere, torus, cone, cylinder, ambientLight, directionalLight, rotateX/Y/Z, and translate(x, y, z).

Events and live values

Define any of these functions in your sketch and they are called automatically:

keyPressed, keyReleased, mousePressed, mouseReleased, mouseClicked, doubleClicked, mouseMoved, mouseDragged, mouseWheel.

Mouse callbacks may either take no parameters or an event argument:

def mousePressed():
    print(mouse.x, mouse.y)

def mouseWheel(event):
    radius += event.delta

Mouse events expose x, y, button, delta, dx, dy, and pos. The live mouse object groups the same state:

mouse.x, mouse.y       # current position
mouse.px, mouse.py     # previous position
mouse.pressed          # button held down
mouse.button           # LEFT / RIGHT / CENTER

Live values are available as bare names (and as attributes such as p5.mouseX):

width, height, displayWidth, displayHeight, windowWidth, windowHeight, mouseX, mouseY, pmouseX, pmouseY, movedX, movedY, mouseButton, mouseIsPressed, mouseWheelDelta, key, keyCode, keyIsPressed, frameCount, deltaTime, pixels, is_Looping.

mouseX and mouseY can be used either as properties (mouseX + 10) or as functions (mouseX()), so both p5.js-style and Processing-style sketches work.

keyCode compares equal to the matching constants (SPACE, LEFT_ARROW, A, ...), while key holds the typed character where available. Use keyIsDown(...) for continuous input:

if keyIsDown(LEFT_ARROW):
    x -= 5

Constants

Constants such as PI, TWO_PI, HALF_PI, TAU, CENTER, CORNER, CORNERS, RADIUS, CLOSE, OPEN, RGB, HSB, LEFT, RIGHT, TOP, BOTTOM, BASELINE, arrow keys, letter/number key codes, BLEND, ADD, MULTIPLY, SCREEN, OVERLAY, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, REPLACE, and the shape-kind constants are all exported by from p5 import *.

Differences from p5.js

  • Rendering uses pygame/Cairo instead of an HTML canvas.
  • LEFT/RIGHT are mouse- and text-alignment constants ("left", "right"). For the arrow keys use LEFT_ARROW/RIGHT_ARROW.
  • loadFont accepts a path to a TrueType/OpenType font; system fonts can be selected by family name.
  • Web-specific APIs (DOM, WEBGL, sound, video) are not implemented.

Project layout

p5/
  color.py        colour parsing, colour modes, fill/stroke
  constants.py    p5 constants, key codes, blend/shape modes
  corefunctions.py  sketch lifecycle, primitives, pixels, images, events
  image.py        PImage, createImage and image pixel helpers
  mathfunctions.py  math, random, noise
  renderer.py     Cairo drawing backend
  settings.py     live sketch state
  timedata.py     date/time helpers
  transform.py    affine transform stack
  vector.py       Vector and createVector

Examples and tests

Runnable sketches live in examples/:

pip install -e .
python examples/basic_shapes.py
python examples/interactive.py
python examples/animation.py

The headless test suite runs without a display:

python -m unittest discover -s tests

License

MIT. See the project page for details and contributions: https://github.com/gromko/p5-python.

Metadata

Release files for p5-python 0.9.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for p5-python 0.9.1
File Size Uploaded Provenance Actions
p5_python-0.9.1.tar.gz 48.6 kB Without provenance Details for p5_python-0.9.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for p5-python 0.9.1
File Interpreter ABI Platform Actions
p5_python-0.9.1-py3-none-any.whl Python 3 none any Details for p5_python-0.9.1-py3-none-any.whl

Total release size: 98.3 kB

Release files / p5_python-0.9.1.tar.gz

Download URL p5_python-0.9.1.tar.gz
Size 48.6 kB
Tags Source
SHA-256 checksum
How to use checksums
96eb9dac4aec2e6f739b62dd8e1694a3a9c10291ee790a3570250e41836aba9e
BLAKE2b-256 checksum
How to use checksums
c52790d6a3c60ce0d0681ceb6d5d30a5c83c36162446fce3b812bd312074b0a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.2

Release files / p5_python-0.9.1-py3-none-any.whl

Download URL p5_python-0.9.1-py3-none-any.whl
Size 49.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ac904aa3107905bace0bdab664709bde4195abc0fb882af0db77c11e429dbb55
BLAKE2b-256 checksum
How to use checksums
5caebb0ef8b7601fd280fdf75ff6c430d2060e829fb898eadd9fbfabe507584b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.2

Security for p5-python 0.9.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page