setCanvasSize(640, 360)
Sets the size of the canvas that all drawings are written to. The first parameter specifies the width in pixels and the second the height. The third parameter is optional and specifies the direction of the y-axis. The constant CARTESIAN can be used to specify a y-axis that is used in maths and a constant of JAVASCRIPT can be used to specify the regular javascript y-axis which moves down the screen. If no value is provided as the third parameter, a default of CARTESIAN is used.
setCanvasSize(w, h, yAxisMode)
width - The width of the canvas in pixels.
height - The height of the canvas in pixels.
yAxisMode - Optionally used to set the direction of the y-axis. Use the constants CARTESIAN or JAVASCRIPT. CARTESIAN is used as the default value if this parameter is not supplied.
noCanvas()
Hides the canvas from the page. This may be useful if you are running a text only Python program.
noCanvas()
This function takes no parameters.
setCanvasSize(640, 360) background(220, 220, 220) input("Press ENTER to continue") focusCanvas()
Places the focus back on the canvas. This is necessary if you wish to receive keyboard events that occur on the canvas and the focus has been moved away. The focus can be moved when a user responds to an input function or clicks away from the canvas. The focus can be returned by the user clicking on the canvas but this function gives you a programmatic way to return focus.
focusCanvas()
This function takes no parameters.
# Draw a rectangle at location (10, 20) with a width of 50 and height of 25. setCanvasSize(100, 100) rect(10, 20, 50, 25)
Draws a rectangle on the canvas. By default, the first two parameters set the location of the bottom left corner, the third sets the width, and the fourth sets the height. The way these parameters are interpreted, may be changed with the rectMode() function. If the setCanvasSize() function is called and sets the yAxisMode to JAVASCRIPT, then the first two parameters specify the top left corner of the rectangle.
rect(x, y, w, h)
x - The x coordinate of the rectangle.
y - The y coordinate of the rectangle.
w - The width of the rectangle.
h - The height of the rectangle.
# Draw a circle at location (100, 200) with a radius of 50. setCanvasSize(200, 400) circle(100, 200, 50)
Draws a circle on the canvas. By default, the first two parameters set the location of the center of the circle, and the third sets the radius. The way these parameters are interpreted, may be changed with the circleMode() function.
circle(x, y, radius)
x - The x coordinate of the circle.
y - The y coordinate of the circle.
radius - The radius of the circle.
# Draw an ellipse at location (100, 200) with an X radius of 50 and a Y radius of 100. setCanvasSize(200, 400) ellipse(100, 200, 50, 100)
Draws an ellipse (oval) on the canvas. By default, the first two parameters set the location of the center of the circle, the third sets the X radius, and the fourth sets the Y radius. The way these parameters are interpreted, may be changed with the circleMode() function.
ellipse(x, y, radiusX, radiusY)
x - The x coordinate of the ellipse.
y - The y coordinate of the ellipse.
radiusX - The X radius of the ellipse.
radiusY - The Y radius of the ellipse.
# Draw an arc at location (50, 50) with an X radius of 40 and a Y radius of 30. The arc spans from 0 to 270 degrees. setCanvasSize(100, 100) arc(50, 50, 40, 30, 0, 270)
Draws an arc (a portion of an ellipse) on the canvas. By default, the first two parameters set the location of the center of the circle, the third sets the X radius, and the fourth sets the Y radius. The fifth parameter is the start angle and the sixth is the end angle. The arc is always drawn clockwise from the start angle to the end angle. The way these parameters are interpreted, may be changed with the circleMode() function. By default the start and end angle are specified in degrees. This can be changed to radians with the angleMode() function.
arc(x, y, radiusX, radiusY, startAngle, endAngle)
x - The x coordinate of the arc.
y - The y coordinate of the arc.
radiusX - The X radius of the arc.
radiusY - The Y radius of the arc.
startAngle - The starting angle of the arc.
endAngle - The ending angle of the arc.
# Draw a line starting at (40, 20) and finishing at (60, 40). setCanvasSize(100, 100) line(40, 20, 60, 40)
# Draw 3 lines of different colours that give a 3D effect. setCanvasSize(640, 360) stroke(0, 0, 0) line(40, 30, 95, 30) stroke(120, 120, 120) line(95, 30, 95, 85) stroke(255, 255, 255) line(95, 85, 40, 85)
Draws an line between two points to the screen. By default the line has a width of a single pixel. This can be modified by the strokeWeight() function. The colour of a line can be changed by calling the stroke() function.
line(x1, y1, x2, y2)
x1 - The x coordinate of the starting point.
y1 - The y coordinate of the starting point.
x2 - The x coordinate of the ending point.
y2 - The y coordinate of the ending point.
# Draw a point at (40, 20). setCanvasSize(100, 100) point(40, 20)
# Draw a blue point at (50, 30) that is 20 pixels in size. setCanvasSize(100, 100) stroke(0, 0, 255) strokeWeight(20) point(50, 30)
Draws a pixel to the screen at the position given by the two parameters. The first parameter specifies the x position and the second parameter specifies the y position. By default the pixel has a size of a one pixel. This can be modified by the strokeWeight() function. The colour of a point can be changed by calling the stroke() function.
point(x, y)
x - The x coordinate.
y - The y coordinate.
# Draw a triangle specified by the three points (50, 75), (25, 100), and (75, 100). setCanvasSize(200, 200) triangle(50, 75, 25, 100, 75, 100)
Draws a triangle on the canvas specified by three points.
triangle(x1, y1, x2, y2, x3, y3)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
x3 - The x coordinate of the third point.
y3 - The y coordinate of the third point.
# Draw a quad specified by the four points (50, 75), (25, 100), (75, 100), and (100, 75). setCanvasSize(200, 200) quad(50, 75, 25, 100, 75, 100, 100, 75)
Draws a quadrilateral (a four sided polygon) on the canvas specified by four points.
quad(x1, y1, x2, y2, x3, y3, x4, y4)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
x3 - The x coordinate of the third point.
y3 - The y coordinate of the third point.
x4 - The x coordinate of the fourth point.
y4 - The y coordinate of the fourth point.
setCanvasSize(640, 360) rectMode(CORNER) fill(0, 0, 255) # draw a blue rectangle with rectMode(CORNER) rect(30, 30, 60, 60) rectMode(CORNERS) fill(255, 0, 0) # draw a red rectangle with rectMode(CORNERS) rect(30, 30, 60, 60)
setCanvasSize(640, 360) rectMode(CENTER) fill(0, 0, 255) # draw a blue rectangle with rectMode(CENTER) rect(30, 30, 60, 60) rectMode(CORNER) fill(255, 0, 0, 0.5) # draw a red rectangle with rectMode(CORNER) rect(30, 30, 60, 60)
Changes the way the rect() function uses the paramters passed to it.
The default mode is CORNER, which indicates that the first two parameters are the coordinates of the bottom left corner, and the third and fourth parameters specify the width and the height. If the setCanvasSize() function is called specifying to set the yAxisMode to JAVASCRIPT, then the first two parameters represent the top left corner.
The mode CORNERS indicates the first two parameters are the coordinates of the bottom left corner, and the third and fourth specify the top right coordinate.
The mode CENTER indicates the first two parameters are the coordinates of the center of the rectangle, and the third and fourth specify the width and height.
rectMode(mode)
mode - Can be CORNER, CORNERS, or CENTER
setCanvasSize(640, 360) circleMode(CENTER) fill(0, 0, 255) # draw a blue circle with circleMode(CENTER) circle(100, 100, 50) circleMode(CORNER) fill(255, 0, 0, 0.5) # draw a red circle with circleMode(CORNER) circle(100, 100, 50)
Changes the way the circle(), ellipse(), and arc() functions use the paramters passed to them.
The default mode is CENTER, which indicates that the first two parameters are the coordinates of the center of the shape. The remaining parameters refer to the radius for the circle() function, and the X radius and Y radius for the ellipse() and arc() functions.
The mode CORNER indicates the first two parameters are the coordinates of the bottom left corner of the shape. The meaning of any extra parameters remain unchanged.
circleMode(mode)
mode - Can be CORNER, or CENTER
setCanvasSize(640, 360) strokeWeight(1) line(10, 10, 100, 10) strokeWeight(2) line(10, 20, 100, 20) strokeWeight(4) line(10, 30, 100, 30) strokeWeight(8) line(10, 40, 100, 40)
Sets the width of any lines, points and the border around shapes. All widths are specified in pixels.
strokeWeight(weight)
weight - the weight of the stroke in pixels.
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
The beginShape(), vertex(), and endShape() functions allow you to create more complex shapes. The beginShape() function starts recording vertices that are added via the vertex() function.
beginShape()
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
The vertex() function adds a point to the list of vertices that will be connected when the endShape() function is called. It takes two parameters, the x and y coordinates of the vertex to add.
vertex(x, y)
x - The x coordinate of the vertex to add.
y - The y coordinate of the vertex to add.
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape(OPEN)
Draws a shape specified by the list of vertices added by calling beginShape() followed by any number of vertex() function calls. By default the entire shape is closed by linking the last vertex back to the first. This can be changed by passing the constant OPEN as a parameter.
endShape(mode)
mode - CLOSE or OPEN. CLOSE specifies the shape should be closed and is the default where OPEN does not connect the last vertex to the first.
Colour(value: int[, alpha: float]) // Greyscale 0–255, optional alpha 0.0–1.0 Colour(r: int, g: int, b: int[, a: float]) // RGB channels 0–255, optional alpha 0.0–1.0 Colour(css: str) // CSS hex, rgb()/rgba(), or named colour Colour(arr: list[int] | tuple[int]) // Python list or tuple of length 3 or 4
The Colour
class represents an RGBA colour. You can create one by:
#RGB
, #RRGGBB
), rgb()
, rgba()
, or any named colour.list
or tuple
of length 3 ([r, g, b]) or 4 ([r, g, b, a]).
c.namedColours
: list<str> – a read-only property on instances that returns all supported CSS colour names.
To inspect:
c = Colour('red') print(c.namedColours) # ['aliceblue', 'antiquewhite', 'aqua', ...]Use these names in
background()
, fill()
, stroke()
, etc.
.red
— Red channel (0–255).green
— Green channel (0–255).blue
— Blue channel (0–255).alpha
— Alpha (0.0–1.0).css(): str
— Returns a CSS-style string "rgba(r, g, b, a)"
.# Numeric RGB c1 = Colour(255, 100, 100) # CSS string c2 = Colour('#f80') c3 = Colour('rgba(10,20,30,0.5)') # Named colour c4 = Colour('hotpink') # Greyscale + alpha c5 = Colour(128, 0.25) # From Python list c6 = Colour([10,20,30,1.0]) print(c4.css()) # "rgba(255, 105, 180, 1.00)" print(len(c1.namedColours), "named colours available")
background(r, g, b[, a]) | background(name: str) | background(col: Colour)
Sets the entire canvas background colour. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string (e.g. 'lavender'
), from a Colour
instance’s namedColours
list.col
: an existing Colour
instance.setCanvasSize(400, 300) # Grey background background(200) # Named-colour background background('lavender') # Using a Colour instance c = Colour('midnightblue', 0.2) background(c) # Draw on top fill('black') text('Hello!', 20, 30)
fill(r, g, b[, a]) | fill(name: str) | fill(col: Colour)
Sets the fill colour for subsequent shapes. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string (e.g. 'red'
), from an Colour
instance’s namedColours
list.col
: an existing Colour
instance.setCanvasSize(640, 360) # RGB fill fill(100, 220, 100) rect(50, 50, 100, 100) # Named-colour fill fill('hotpink') ellipse(200, 200, 80, 80) # Colour-instance fill c = Colour('navy', 0.5) fill(c) rect(300, 50, 80, 120)
noFill()
Disables filling of shapes. After calling noFill()
, shapes will be drawn with transparent interiors.
Use stroke()
to set the outline colour.
setCanvasSize(300, 200) stroke('blue') noFill() rect(50, 50, 200, 100)
stroke(r, g, b[, a]) | stroke(name: str) | stroke(col: Colour)
Sets the outline (stroke) colour for shapes and lines. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string.col
: an existing Colour
instance.setCanvasSize(300, 200) # Black outline by default stroke(0) noFill() ellipse(150, 100, 100, 100) # Semi-transparent red outline stroke('red', 0.5) rect(50, 50, 200, 100)
noStroke()
Disables drawing outlines for shapes. After calling noStroke()
, shapes will only fill interiors.
Use fill()
to set the fill colour.
setCanvasSize(300, 200) fill('green') noStroke() rect(50, 50, 200, 100)
pyangelo = Image("/samples/images/PyAngelo.png") setCanvasSize(640, 360) x = width/2 - 64 y = height/2 - 48 while True: background(255, 255, 0) drawImage(pyangelo, x, y) text("Use the WASD keys to move me around!", 20, 30) if isKeyPressed(KEY_W): y -= 1 if isKeyPressed(KEY_A): x -= 1 if isKeyPressed(KEY_S): y += 1 if isKeyPressed(KEY_D): x += 1 sleep(0.005)
Returns True if the key specified by the first parameter is currently pressed, otherwise returns False. Once the key has been pressed the function will continue to return True each time it is called until the key is released. There is a list of constants that can be used in PyAngelo to represent each key for clarity.
isKeyPressed(code)
code - The code representing a key on the keyboard. See a list of codes.
pyangelo = Image("/samples/images/PyAngelo.png") setCanvasSize(640, 360) x = width/2 - 64 y = height/2 - 48 while True: background(255, 255, 0) drawImage(pyangelo, x, y) text("Use the WASD keys to move me around!", 20, 30) if wasKeyPressed(KEY_W): y -= 1 if wasKeyPressed(KEY_A): x -= 1 if wasKeyPressed(KEY_S): y += 1 if wasKeyPressed(KEY_D): x += 1 sleep(0.005)
Returns True if the key specified by the first parameter has been pressed and not yet released before this function is called. Otherwise, it returns False. Once the key has been pressed and the function has been called, the function will then return False until the key is pressed again. This is different from the isKeyPressed() function which continues to return True when called until the key is released. There is a list of constants that can be used in PyAngelo to represent each key for clarity.
wasKeyPressed(code)
code - The code representing a key on the keyboard. See a list of codes.
This variable holds the current horizontal position of the mouse. The value is the number of pixels from the origin (0, 0) of the canvas.
mouseX
This variable holds the current vertical position of the mouse. The value is the number of pixels from the origin (0, 0) of the canvas.
mouseY
This boolean variable is True when the mouse is currently pressed, otherwise it is False.
mouseIsPressed
setCanvasSize(400, 400) forever: if wasMousePressed(): print("Mouse was pressed") sleep(0.005)
Returns True if the mouse has been pressed and not yet released before this function is called. Otherwise, it returns False. Once the mouse has been pressed and the function has been called, the function will then return False until the mouse is pressed again. This is different from the mouseIsPressed inbuilt boolean variable which continues to be set to True until the mouse is released.
wasMousePressed()
This function takes no parameters.
Functions for loading and selecting fonts, and drawing text.
setCanvasSize(400, 100) background(220, 220, 220) text("I love PyAngelo!", 20, 30)
setCanvasSize(800, 100) background(220, 220, 220) text("I'm a new font that is big!", 20, 30, 50, 'Times New Roman')
Draws text to the screen. The first 3 parameters are mandatory. The first specified the text to display. The second is the x position and the third is the y position. The fourth parameter is optional and is the size of the text. This defaults to 20 pixels. The fifth parameter is optional is the font to use. The font defaults to Arial.
text(text, x, y, fontSize, fontName)
text - The text to display.
x - The x position of the top left of the text.
y - The y position of the top left of the text.
fontSize - The size of the text in pixels.
fontName - The type of font to use when displaying the text.
setCanvasSize(450, 100) background(220, 220, 220) myFont = loadFont("/samples/fonts/arcade.ttf") text("I love PyAngelo!", 20, 30, 50, myFont)
Loads a font to the screen as specified in the first parameter.
myFont = loadFont(filename)
filename - The font file.
setCanvasSize(450, 100) background(220, 220, 220) myFont = loadFont("/samples/fonts/arcade.ttf") setFont(myFont) text("I love PyAngelo!", 20, 30, 50)
Sets the default font to use if one is not specified when calling text()
setFont(font)
font - The default font to use. Can be a font you have loaded or a font that is available in your browser.
Sets the alignment for subsequent text()
calls.
setCanvasSize(500, 100) background(220, 220, 220) myFont = loadFont("/samples/fonts/arcade.ttf") setFont(myFont) textAlign(CENTER, CENTER) text("I love PyAngelo!", width/2, height/2, 50)
Aligns any subsequent text calls()
textAlign(horizontal, vertical)
horizontal
LEFT
CENTER
RIGHT
vertical
TOP
CENTER
BOTTOM
BASELINE
setCanvasSize(300, 300) hero = Image("/samples/images/PyAngelo.png") hero.draw(50, 100) hero.dispose()
Loads an image into memory which can later be displayed with the draw(), drawRegion(), drawSubImage(), or drawFrame() methods. Use dispose() to unload the image and free its resources when no longer needed.
file - The location of the image file to load.
Alias for Image(file)
.
alpha - Number between 0 (transparent) and 1 (opaque).
angle - Rotation angle in radians (or degrees if angleMode is set to DEGREES).
scaleX - Horizontal scale factor.
scaleY - Vertical scale factor (optional; defaults to scaleX).
frameW - Width of each frame in a sprite sheet.
frameH - Height of each frame.
flag - 0 or false to disable horizontal flip, 1 or true to enable.
flag - 0 or false to disable vertical flip, 1 or true to enable.
ox - X coordinate of the pivot point or the string "center".
oy - Y coordinate of the pivot point or "center" (optional; defaults to ox).
x - X coordinate where the image’s origin will be placed.
y - Y coordinate where the image’s origin will be placed.
width - Optional drawing width (defaults to image.width).
height - Optional drawing height (defaults to image.height).
sx, sy - Source x and y of the sub-region.
sw, sh - Width and height of the source sub-region.
dx, dy - Destination x and y on the canvas.
dw, dh - Optional destination width and height (defaults to sw and sh).
subImage - A SubImage
instance defining the source rectangle to draw.
x, y - Destination coordinates on the canvas.
w, h - Optional drawing width and height (defaults to the sub-region’s width
and height
).
index - Frame index in the sprite sheet (0-based).
x, y - Destination coordinates on the canvas.
scaleW, scaleH - Optional scaling of the frame (defaults to frameWidth and frameHeight).
Release the image’s underlying resources and remove it from memory.
Each image object has the following public properties:
# Example 1: Rotating and scaling an image setCanvasSize(400, 400) hero = Image("/samples/images/PyAngelo.png") hero.setRotation(90) hero.setPivot('center') hero.setScale(1.5) hero.draw(150, 150) hero.dispose() # Example 2: Drawing a sprite sheet frame setCanvasSize(400, 400) setImageSmoothing(False) sprites = Image("/samples/images/alien-spritesheet.png") sprites.setFrameSize(16, 20) sprites.drawFrame(4, 100, 200, 160, 200) sprites.dispose() # Example 3: Drawing a sub-region of a larger image setCanvasSize(400, 400) bg = Image("/samples/endless-runner/gameOverBackground.png") bg.drawRegion(50, 50, 100, 100, 300, 300) bg.dispose()
setImageSmoothing(False)
Enables or disables image smoothing when scaling images. Pass True to enable smoothing or False for pixelated scaling.
enabled - True or False. Use True if you wish to enable image smoothing, use False if you want pixel scaling with no smoothing for pixel art.
SubImage(x, y, width, height)
Defines a rectangular region within an existing Image
object.
.x
(int).y
(int).width
(int).height
(int)sub = SubImage(10, 20, 30, 40) print(sub)
# Define a sub-region and draw it using drawSubImage img = Image("/samples/images/alien-spritesheet.png") sub = SubImage(64, 0, 16, 20) setCanvasSize(400, 400) setImageSmoothing(False) background() img.drawSubImage(sub, 100, 150, 160, 200)
setCanvasSize(640, 360) background(220, 220, 220) translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) angleMode(RADIANS) rotate(1) rect(0, 0, 50, 50)
Sets the type of angle to use in many functions. This takes 1 parameter and it is suggested to use the constants of DEGREES and RADIANS when calling this function for clarity.
angleMode(mode)
mode - an integer where 1 represents RADIANS and 2 represents DEGREES.
setCanvasSize(640, 360) background(220, 220, 220) rect(0, 0, 50, 50) # Draw rect at original 0,0 translate(50, 50) rect(0, 0, 50, 50) # Draw rect at new 0,0 translate(25, 10) rect(0, 0, 50, 50) # Draw rect at new 0,0
Moves the position of the origin. The first parameter specifies the number of pixels along the x axis, and the second paramter specifies the number of pixels along the y axis.
If tranlate is called twice, the effects are cumulative. So calling translate(10, 10) followed by translate(20, 20) is the same as calling translate(30, 30). The saveState() and restoreState() functions can be used to save and restore transformations.
translate(x, y)
x - The number of pixels to move the origin along the x axis.
y - The number of pixels to move the origin along the y axis.
setCanvasSize(640, 360) background(220, 220, 220) translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50)
Rotates the shape by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function.
Shapes are rotated around the origin. Positive numbers rotate in a clockwise direction. Rotations are cumulative so calling rorate(45) followed by rotate(30) is the same as calling rotate(75). The saveState() and restoreState() functions can be used to save and restore transformations.
rotate(angle)
angle - The number of of degrees or radians to rotate the shape depending on the angleMode.
setCanvasSize(640, 360) fill(100, 220, 100, 0.5) for i in range(5): applyMatrix(1, i*0.1, i*-0.1, 1, i*30, i*10) rect(0, 0, 250, 100)
The applyMatrix() method lets you scale, rotate, move, and skew the current context.
applyMatrix(a, b, c, d, e, f)
a - Horizontal scaling
b - Horizontal skewing
c - Vertical skewing
d - Vertical scaling
e - Horizontal moving
f - Vertical moving
setCanvasSize(640, 360) translate(250, 200) shearX(45) rect(0, 0, 30, 30)
Skews the shape around the x-axis by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function. The skew is relative to the origin.
shearX(angle)
angle - The number of of degrees or radians to shear the shape around the x-axis depending on the angleMode.
setCanvasSize(640, 360) translate(250, 200) shearY(45) rect(0, 0, 30, 30)
Skews the shape around the y-axis by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function. The skew is relative to the origin.
shearY(angle)
angle - The number of of degrees or radians to shear the shape around the y-axis depending on the angleMode.
setCanvasSize(640, 360) background(220, 220, 220) saveState() translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50) restoreState() rectMode(CORNER) rect(0, 0, 50, 50)
Saves the current drawing style settings and transformations. These can be restored using the restoreState() function. This allows you to change the style and transformation settings and then return to the previous version of these settings.
This function saves the settings of the fill(), stroke(), strokeWeight(), translate(), and rotate() functions.
saveState()
setCanvasSize(640, 360) background(220, 220, 220) saveState() translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50) restoreState() rectMode(CORNER) rect(0, 0, 50, 50)
Restores the latest version of the drawing style settings and transformations. To save these settings the saveState() function must be used. This allows you to change the style and transformation settings and then return to the previous version of these settings.
This function restores the previously saved settings of the fill(), stroke(), strokeWeight(), translate(), and rotate() functions.
restoreState()
setConsoleSize(SMALL_SCREEN)
setConsoleSize(MEDIUM_SCREEN)
setConsoleSize(LARGE_SCREEN)
Sets the size of the console in pixels. The first and only parameter is an integer that must be between between 100 and 2000. The PyAngelo constants of SMALL_SCREEN (100), MEDIUM_SCREEN (500), and LARGE_SCREEN (1000) can be used.
setConsoleSize(size)
size - The height of the console in pixels.
setTextSize(SMALL_FONT)
setTextSize(MEDIUM_FONT)
setTextSize(LARGE_FONT)
Sets the size of the text printed to the console in pixels. The first and only parameter is an integer that must be between between 8 and 128. The PyAngelo constants of SMALL_FONT (8), MEDIUM_FONT (16), and LARGE_FONT (24) can be used.
setTextSize(size)
size - The size of the text in pixels.
setTextColour(RED) print("I am red.")
Sets the text colour for any print statements which will be output on the console. The following constants should be used as a parameter:
setTextColour()
colour - An integer between 1 and 22 represeting the colour. The above constants should be used for clarity.
setTextColour(RED) setHighlightColour(WHITE) print("I am red text on a white background.")
Sets the highlight or background colour for any print statements which will be output on the console. The following constants should be used as a parameter:
setHighlightColour()
colour - An integer between 1 and 22 represeting the colour. The above constants should be used for clarity.
print("I am displayed but will be removed after 1 second. Help!") sleep(1) clear()
clear(RED)
Clears the console.
clear(colour)
colour - The colour of the console after the screen is cleared. This is an optional parameter. If no colour is specified, a black colour will be displayed. The parameter is an integer from 1 to 22 but the following constants should be used for clarity:
Sprites are drawable objects—images, shapes, or text—that support positioning, sizing, rotation, collision, and more. All sprite types inherit shared properties and methods, while each subclass adds its own constructor signature and behavior.
To use any of the following classes, import the module:
from sprite import *
x, y
drawMode
).width, height
angle
anchorX
·width
, anchorY
·height
).opacity
drawMode
CORNER
(x, y = bottom‐left) or CENTER
(x, y = center).anchorX, anchorY
draw()
moveTo(x, y)
moveBy(dx, dy)
setDrawMode(mode)
CORNER
or CENTER
for drawing and collision detection.setAnchor(xFrac, yFrac)
anchorX
and anchorY
.rotateBy(delta)
delta
degrees or radians to angle
.rotateTo(angle)
angle
absolutely.contains(point)
True
if point is inside the sprite’s hitbox.overlaps(other)
True
if this sprite’s hitbox overlaps another.Base class for image sprites loaded from assets/
.
Sprite(imageFile, x, y, width, height)
hitboxScale
setHitboxScale(scale)
scale
before collision checks.Text label with font and textAlign support.
TextSprite(text, x, y, fontSize, fontName)
textContent
— the string being drawnfontSize
— current text sizefontName
— current font familyAxis-aligned rectangle.
RectangleSprite(x, y, width, height)
CORNER
anchoring.Circle defined by center and radius.
CircleSprite(x, y, radius)
CENTER
anchoring.Ellipse defined by X/Y radii.
EllipseSprite(x, y, radiusX, radiusY)
CENTER
anchoring.Regular N-gon by number of sides and radius.
PolygonSprite(x, y, numSides, radius)
CENTER
anchoring.from sprite import *
setCanvasSize(400, 300)
r = RectangleSprite(50, 50, 100, 60)
p = PolygonSprite(200, 150, numSides=6, radius=40)
r.draw()
p.draw()
# collision test
print(r.overlaps(p))
from sprite import *
setCanvasSize(400, 300)
# ellipse in CORNER mode at top-left
e = EllipseSprite(10, 10, 80, 40)
e.setDrawMode(CORNER)
e.draw()
# circle centered
c = CircleSprite(200, 150, 30)
c.draw()
from sprite import *
setCanvasSize(500, 400)
background(40, 52, 54)
img = Sprite('/samples/images/blue-alien-idle.png', 100, 100, 128, 128)
img.draw()
textAlign(CENTER)
t = TextSprite('Welcome', 100, 200, 32)
t.setColour(255, 0, 0)
t.draw()
from sprite import *
setCanvasSize(500, 400)
poly = PolygonSprite(250, 200, 8, 50)
poly.setColour('hotpink')
forever:
background(40)
poly.moveBy(1, 0)
if poly.left > width:
poly.x = -poly.radius
poly.rotateBy(-1)
poly.draw()
strokeWeight(4)
stroke('purple')
line(0, 150, width, 150)
fill('lightgrey')
noStroke()
textAlign(CENTER, TOP)
text("Rotating Octagon", 250, height, 50)
sleep(1/60)
from sprite import *
setCanvasSize(300, 200)
alien = Sprite("/samples/images/blue-alien-idle.png", 150, 100)
r = RectangleSprite(150, 100, 80, 40)
r.setDrawMode(CENTER)
r.setColour('purple')
while True:
background(40)
if isKeyPressed(KEY_A):
alien.moveBy(-1, 0)
if isKeyPressed(KEY_D):
alien.moveBy(1, 0)
if isKeyPressed(KEY_W):
alien.moveBy(0, 1)
if isKeyPressed(KEY_S):
alien.moveBy(0, -1)
if alien.overlaps(r):
fill('red')
noStroke()
textAlign(CENTER, BOTTOM)
text('Overlaps', width/2, 0, 50)
alien.draw()
r.draw()
sleep(1/60)
from sprite import *
setCanvasSize(640, 360)
pyangelo = Sprite("/samples/images/PyAngelo.png", 100, 75)
pyangelo.setHitboxScale(0.8)
alien = Sprite("/samples/images/blue-alien-idle.png", 300, 75)
fill(253,248,126)
noStroke()
textAlign(CENTER, TOP)
while True:
background(167,29,239)
pyangelo.draw()
noFill()
stroke(0)
rect(pyangelo.left, pyangelo.bottom, pyangelo.width * pyangelo.hitboxScale, pyangelo.height * pyangelo.hitboxScale)
alien.draw()
rect(alien.left, alien.bottom, alien.width, alien.height)
if isKeyPressed(KEY_A):
alien.moveBy(-1, 0)
if isKeyPressed(KEY_D):
alien.moveBy(1, 0)
if isKeyPressed(KEY_W):
alien.moveBy(0, 1)
if isKeyPressed(KEY_S):
alien.moveBy(0, -1)
if pyangelo.overlaps(alien):
fill(253,248,126)
noStroke()
text("Overlapping!", width/2, height, fontSize=50)
sleep(1/60)
All sprite instances support a built-in tweenTo()
method to animate numeric properties over time. This is the preferred way to animate sprites.
# animate x to 200 over 2 seconds, then y to 150 over 1.5 seconds
from sprite import *
from time import time
setCanvasSize(400, 400)
r = RectangleSprite(0, 0, 50, 50)
r.tweenTo('x', 200, 2.0).onComplete(lambda: print("X done!"))
r.tweenTo('y', 150, 1.5).onComplete(lambda: print("Y done!"))
# In your main loop:
lastTime = time()
while True:
now = time()
dt = now - lastTime
lastTime = now
background(40)
r.update(dt) # advances all tweens registered via tweenTo
r.draw()
sleep(max(0, 1/60 - (time() - now)))
If you need to use the Tween
class directly, you can—but for most cases tweenTo()
on the sprite is simpler and ensures the tween is managed automatically.
In simple loops, you can throttle to a fixed FPS by using sleep()
setCanvasSize(640, 360)
x = 0
radius = 50
noStroke()
fill(255, 255, 0, 0.7)
while True:
background(0, 0, 0)
circle(x, 180, radius)
x += 1
if x > width + radius:
x = -radius
sleep(1/60)
The sleep() function causes the program to suspend for the number of seconds specified by the first parameter. This is extremely useful for animation purposes inside a while loop as shown in the example above. Try changing some of the variables in the program to see the effect it has.
sleep(delay)
delay - The number of seconds to delay the program for.
DeltaTimer automatically measures the true time between frames (dt) and lets you both throttle to a target FPS and query the current or smoothed frame rate.
from deltaTimer import DeltaTimer
# Target 60 FPS, smooth FPS reading over last 30 frames
timer = DeltaTimer(fps=60, smoothing=30)
from deltaTimer import DeltaTimer
timer = DeltaTimer()
setCanvasSize(640, 360)
x = 0
radius = 50
# Ball speed in pixels per second
# It should take 2 seconds to go across the screen
SPEED = 320
noStroke()
fill(255, 255, 0, 0.7)
while True:
dt = timer.update()
background(0, 0, 0)
circle(x, 180, radius)
x += SPEED * dt
if x > width + radius:
x = -radius
fill(0, 255, 0)
fps = round(timer.getFps())
text("FPS: " + str(fps), 10, height - 50, 50)
timer.enforceFps()
Call at the start of each frame/iteration.
Returns dt (float): elapsed seconds since the last call to update() (or since creation/resume).
If the timer is paused, returns 0.0 and does not update the internal clock.
Call at the end of each frame/iteration.
Sleeps for the remainder of the frame budget (1/fps - work_time).
If the frame work took longer than the budget, returns immediately (no negative sleep).
If paused, still sleeps exactly one frame’s worth (1/fps).
Pauses the timer. Subsequent update() calls return 0.0 until resume() is called.
Resumes timing, resetting the internal last-time so that next update() has no large jump.
With DeltaTimer, you get both accurate motion based on real elapsed time and smooth, reliable FPS throttling—without re-writing your loop logic or manually calculating sleeps.
# Load a sound file and keep the object music = Sound("/samples/music/Myth.mp3") # Play, pause, and stop control: music.play() music.pause() music.stop()
Creates a new Sound
instance for the given file URL. You can then call methods on that instance to control playback, volume, looping, etc.
filename
– A string URL to the sound file.sound.play() # start or resume playback
Starts or resumes the sound. If the sound was paused, it picks up from where it left off; otherwise it begins at the current seek position (default 0.0).
sound.pause() # temporarily halt playback
Pauses the sound at its current position. A subsequent play()
will resume from this point.
sound.stop() # halt and reset position to 0.0
Stops playback and resets the playhead to the start (0.0 seconds). Loop and volume settings remain unchanged.
Returns True
if the sound is currently playing (not paused), otherwise False
.
Without arguments, returns the current playhead position in seconds (0.0 before play). With a position
argument (in seconds), jumps to that time and returns None
.
When called without arguments, returns the current playback rate (a multiplier, default 1.0). With speed
> 0, sets a new rate (e.g. 2.0 for double speed) and returns None
.
Without arguments, returns the current volume (0.0–1.0). With level
between 0.0 and 1.0, sets the volume and returns None
.
With no arguments, returns whether looping is currently enabled. With state
=True
or False
, toggles looping and returns None
.
Without arguments, returns current mute state. With a boolean state
, mutes or unmutes the sound.
Fade volume from from
→to
(both 0.0–1.0) over duration
seconds.
Returns the total length of the sound in seconds.
Stops playback (if any), unloads the audio from memory, and removes the instance from internal registries.
# static call on the class: Sound.stopAll() # or from an instance: music.stopAll()
Stops every Sound
instance currently registered, no matter what file they’re playing.
# Create and configure a Sound music = Sound("/samples/music/Myth.mp3") music.volume(0.5) # half volume music.loop(True) # repeat forever music.play() # …later, pause and inspect… music.pause() print("At", music.seek(), "seconds") # and finally stop everything Sound.stopAll()
This variable holds the width of the canvas. The default width of the canvas is 500 pixels and can be changed by calling the setCanvasSize() function.
width
This variable holds the height of the canvas. The default height of the canvas is 400 pixels and can be changed by calling the setCanvasSize() function.
height
This variable holds the width of the web browser's window minus 15 pixels.
windowWidth
This variable holds the height of the web browser's window minus 15 pixels.
windowHeight
setCanvasSize(100, 100) forever: background(200) leftWall = 25 rightWall = 75 # xm is just the mouseX, while # xc is the mouseX, but constrained # between the leftWall and rightWall! xm = mouseX xc = constrain(mouseX, leftWall, rightWall) # Draw the walls. stroke(150, 150, 150) line(leftWall, 0, leftWall, height) line(rightWall, 0, rightWall, height) # Draw xm and xc as circles. noStroke() fill(150, 150, 150) ellipse(xm, 33, 9, 9) # Not Constrained fill(0, 0, 0) ellipse(xc, 66, 9, 9) # Constrained
Constrains a value between a minimum and maximum value.
constrain(n, low, high)
n - The number to constrain
low - The minimum limit
high - The maximum limit
from math import * setCanvasSize(500, 400) fill(0, 0, 0) x1 = 20 y1 = height - 50 angleMode(RADIANS) while True: saveState() background(220, 220, 220) x2 = mouseX y2 = mouseY line(x1, y1, x2, y2) circle(x1, y1, 5) circle(x2, y2, 5) d = int(dist(x1, y1, x2, y2)) # Let's write d along the line we are drawing translate((x1+x2)/2, (y1+y2)/2) rotate(atan2(y2-y1, x2 - x1)) text(d, 0, -20) restoreState()
Calculates the distance between two points.
dist(x1, y1, x2, y2)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
from math import * setCanvasSize(500, 400) while True: r = mapToRange(mouseX, 0, width, 0, 255) fill(int(r), 0, 0) circle(width/2, height/2, 50) sleep(0.005)
Re-maps a number from one range to another.
mapToRange(value, start1, stop1, start2, stop2, withinBounds)
value - The incoming value to be converted.
start1 - The lower bound of the current range.
stop1 - The upper bound of the current range.
start2 - The lower bound of the target range.
stop2 - The upper bound of the target range.
withinBounds - Should the value be constrained to the target range.
QUARTER_PI is a mathematical constant with a value of 0.7853982.
HALF_PI is a mathematical constant with a value of 1.57079632679489661923.
PI is a mathematical constant with a value of 3.14159265358979323846.
TWO_PI is a mathematical constant with a value of 6.28318530717958647693.
TAU is a mathematical constant with a value of 6.28318530717958647693. It is equal to TWO_PI.
DEGREES is a constant that is used with the angleMode() function to inform PyAngelo to use degrees for the rotate() and arc() functions.
RADIANS is a constant that is used with the angleMode() function to inform PyAngelo to use radians for the rotate() and arc() functions.
CARTESIAN is a constant that is used with the setCanvasSize() function to inform PyAngelo to use a maths based y-axis where the y value increases as you move up the canvas.
JAVASCRIPT is a constant that is used with the setCanvasSize() function to inform PyAngelo to use a JavaScript based y-axis where the y value increases as you move down the canvas.
KEY_A through to KEY_Z are constants that can be used with the isKeyPressed function to check if the A through to the Z key has been pressed. In addition there is also KEY_SPACE, KEY_ENTER, KEY_ESCAPE, KEY_DEL, KEY_BACKSPACE, KEY_TAB, KEY_LEFT, KEY_RIGHT, KEY_UP and KEY_DOWN.