Function index

Every name a Pyctures program can use, by area, one line each. The link on each row goes to the page that explains it, with examples.

Areapictures.jsPyctures
2D drawing: the plain functionsYesYes
2D drawing: the canvas, ctxYesYes
3D: three.jsYesYes
Sprites and hit-testingYesYes
Keyboard, mouse and touchYesYes
Frames and timingYesYes
Saved valuesYesYes
FilesYesYes
Databases (SQLite)YesYes
Image processingYes In Circuitry onlyYes In Circuitry only
ScenesYesYes
Sound and musicYesYes
Dials, sliders and a keyboardYesYes
Sheet musicYesYes
EffectsYesYes

This page is Pyctures's own index, in its own spellings. pictures.js has the same areas in JavaScript: the pictures.js function index.

Everything here works everywhere Circuitry runs (iPhone, iPad, Android, the desktop app and a web browser) and in a page made with File, Export as Web Page, unless its row has a badge that says otherwise. In Circuitry only means inside Circuitry, and not in the Pyctures library used on its own or in an exported page.

The shape of a program

Functions you write. They are called if the program defines them.

Explained in How a program is shaped.

NameWhat it does
setup()Called once, before the first frame
update(dt)Called every frame, with the seconds since the last one: move things here
draw()Called every frame, after update: draw the picture here

Scenes

A program in several scenes, each with the functions above as its own. Only a file that uses one of these names is given them.

NameWhat it doesMore
class Title(Scene):A scene: setup, update, draw and the on_ functions as its own, its variables on self. Every Scene class plays, in the order writtenScenes
scene(name, draw=, update=, …)A scene from plain functions, with no classScenes
go(scene)Change to a scene, by its name or its class. It can say a transition, and keep goes back to a scene as it was leftScenes
next_scene()Change to the next scene written; after the last comes the firstScenes
restart()Begin this scene again, from emptyScenes
resume(self)A scene's own: called in place of setup() when it is come back to with keep. Controls are made again hereScenes
length, beats, barsOn a scene: it ends by itself after so many seconds, beats or barsScenes
scene_time, scene_progress, scene_nameSeconds since this scene began, how far through its length it is (0 to 1), and its nameScenes
transition, transition_time, transition_colorOn a scene: how it arrives. "cut", "crossfade", "fade", the wipes and the slidesScenes
config(…)Settings for every scene: loop, transition, transition_time, transition_color, beats_per_barScenes
section(name)A tick on the scrubber at this momentScenes
on_seek(seconds)A function you write at the top level: called when the scrubber is movedScenes

2D drawing: the plain functions

One call each, with no ctx. in front.

Explained in 2D functions.

NameWhat it does
background(colour)Paints the whole canvas
circle(x, y, radius, colour)A filled circle centred on x, y
ellipse(x, y, width, height, colour)An oval centred on x, y
rect(x, y, width, height, colour)A filled rectangle, top-left corner at x, y
triangle(x1, y1, x2, y2, x3, y3, colour)A triangle, by its three corners
polygon(x, y, radius, sides, colour)A shape with that many equal sides, centred on x, y, one corner straight up
star(x, y, radius, points, colour)A star with that many points, one straight up
line(x1, y1, x2, y2, colour, thickness)A straight line
text(words, x, y, colour, size, align)Words, size points high
picture(what, x, y, size)An emoji or a word, an image file beside the program, or a loaded image, centred on x, y and …

Chance and angles

Explained in 2D functions.

NameWhat it does
random(min, max)A whole number from min to max, either end included
random(max), random()From 0 to max; with nothing, a fraction from 0 up to 1
pick(list)One thing from a list, by chance
degrees(n)An angle said in degrees, wherever an angle is wanted: ctx.rotate(degrees(45)), ship.angle = …

2D drawing: the canvas, ctx

The web's own 2D drawing surface: everything the plain functions do, and much more.

Size and pictures

Explained in 2D functions.

NameWhat it does
width, heightThe size of the preview, in points
pixel_ratioReal pixels per point (2 or 3 on most phones)
canvasThe preview's canvas, for canvas.add_event_listener(...)
load_image(address)Loads a picture to draw
jsEverything else the preview page has, such as js.Path2D and js.document

Rectangles

Explained in 2D functions.

NameWhat it does
ctx.fill_rect(x, y, w, h)A filled rectangle, top-left corner at x, y
ctx.stroke_rect(x, y, w, h)The outline of a rectangle
ctx.clear_rect(x, y, w, h)Rubs that area out, back to see-through

Paths

Explained in 2D functions.

NameWhat it does
ctx.begin_path()Starts a new, empty path
ctx.move_to(x, y)Lifts the pen and puts it down at x, y
ctx.line_to(x, y)A straight line to x, y
ctx.close_path()A straight line back to where this piece started
ctx.rect(x, y, w, h)A rectangle, as part of the path
ctx.round_rect(x, y, w, h, r)A rounded rectangle
ctx.arc(x, y, r, start, end)Part of a circle round x, y, from angle start to end in radians (0 to math.tau is all …
ctx.arc_to(x1, y1, x2, y2, r)A rounded corner of radius r, turning at x1, y1 towards x2, y2
ctx.ellipse(x, y, rx, ry, turn, start, end)Part of an oval, rx wide and ry tall, turned by turn radians
ctx.quadratic_curve_to(cx, cy, x, y)A curve to x, y, pulled towards one control point
ctx.bezier_curve_to(c1x, c1y, c2x, c2y, x, y)A curve to x, y with two control points
ctx.fill()Fills the path
ctx.stroke()Draws the path's outline

Colours and styles

Explained in 2D functions.

NameWhat it does
ctx.fill_style = …The colour, gradient or pattern for fills and filled text
ctx.stroke_style = …The same, for outlines
ctx.global_alpha = 0.5How solid everything drawn next is, from 0 (invisible) to 1
ctx.create_linear_gradient(x0, y0, x1, y1)A gradient along a line
ctx.create_radial_gradient(x0, y0, r0, x1, y1, r1)A gradient between two circles
ctx.create_conic_gradient(angle, x, y)A gradient round a point, like a colour wheel
gradient.add_color_stop(position, colour)A colour at a point (0 to 1) along a gradient
ctx.create_pattern(picture, "repeat")A repeating fill from a picture or another canvas

Lines: width, ends, corners and dashed lines

Explained in 2D functions.

NameWhat it does
ctx.line_width = 4How thick outlines are, in points
ctx.line_cap = "round"How line ends look: "butt" (flat, stops at the end), "round", "square" (flat, sticks out …
ctx.line_join = "round"How corners look: "miter" (sharp), "round", "bevel" (cut off)
ctx.miter_limit = 10How far a sharp corner may stick out before it is cut off like a bevel
ctx.set_line_dash([10, 5])Dashes: 10 drawn, 5 gap
await ctx.get_line_dash()(await) The current dash list
ctx.line_dash_offset = 4Slides the dashes along

Text: drawing it, fonts and measuring text width

Explained in 2D functions.

NameWhat it does
ctx.fill_text(text, x, y)Draws text
ctx.stroke_text(text, x, y)Draws the outline of the text
await ctx.measure_text(text).width(await) How wide the text will be, in points
ctx.font = "bold 24px serif"Style, size and family
ctx.text_align = "center"Where x is: "left", "center", "right", or "start"/"end" (which follow the writing …
ctx.text_baseline = "middle"Where y is: "alphabetic" (the line letters sit on, the default), "top", "hanging" …
ctx.direction = "rtl"Writing direction: "ltr", "rtl" or "inherit"
ctx.letter_spacing = "4px"Extra space between letters (older devices ignore it)
ctx.word_spacing = "10px"Extra space between words (older devices ignore it)
ctx.font_kerning = "none"Whether letter pairs are fitted closer: "auto", "normal", "none"

Images

Explained in 2D functions.

NameWhat it does
img = load_image(address)Starts loading a picture from a web address (asked about first: what a program can reach) or a …
ctx.draw_image(img, x, y)Draws it at its own size, top-left at x, y
ctx.draw_image(img, x, y, w, h)Draws it stretched to w by h
ctx.draw_image(img, sx, sy, sw, sh, x, y, w, h)Cuts the part sx, sy, sw, sh out of the picture and draws it at x, y, w, h
ctx.image_smoothing_enabled = FalseKeeps pixel art crisp and blocky when scaled up
ctx.image_smoothing_quality = "high"How carefully pictures are smoothed: "low", "medium", "high"

Transforms

Explained in 2D functions.

NameWhat it does
ctx.translate(x, y)Moves the grid's corner (0, 0) to x, y
ctx.rotate(angle)Turns the grid round (0, 0) by angle radians, clockwise
ctx.scale(sx, sy)Stretches the grid
ctx.transform(a, b, c, d, e, f)Applies any stretch, slant and move at once
ctx.save()Remembers the transform and every setting on this page
ctx.restore()Goes back to what the last save() remembered
ctx.set_transform(a, b, c, d, e, f)Replaces the transform completely
ctx.reset_transform()Clears the transform
await ctx.get_transform()(await) The current transform, as numbers a to f

Shadows

Explained in 2D functions.

NameWhat it does
ctx.shadow_color = "rgba(0, 0, 0, 0.5)"The shadow's colour
ctx.shadow_blur = 10How soft the shadow is
ctx.shadow_offset_x = 5How far right the shadow falls
ctx.shadow_offset_y = 5How far down the shadow falls

Blending and filters

Explained in 2D functions.

NameWhat it does
ctx.global_composite_operation = "multiply"How new drawing mixes with what is already there
ctx.filter = "blur(4px)"An effect on everything drawn next

Clipping and hit testing

Explained in 2D functions.

NameWhat it does
ctx.clip()Makes the current path a window: everything drawn next shows only inside it
await ctx.is_point_in_path(x, y)(await) Whether a point is inside the current path
await ctx.is_point_in_stroke(x, y)(await) Whether a point is on the path's outline

Paths you can keep: Path2D

Explained in 2D functions.

NameWhat it does
ctx.fill(path)Fills that path
ctx.stroke(path)Outlines it
ctx.clip(path)Clips to it
await ctx.is_point_in_path(path, x, y)(await) Whether a point is inside it
path.add_path(other)Adds another path's pieces to this one

Pixels

Explained in 2D functions.

NameWhat it does
await ctx.get_image_data(x, y, w, h).data(await) The colours of every pixel in that area, as one long list: red, green, blue, alpha …
ctx.create_image_data(w, h)A blank block of pixels
ctx.put_image_data(pixels, x, y)Puts a block of pixels straight onto the canvas, ignoring transforms, alpha and blend modes
js.ImageData(js.Uint8ClampedArray(numbers), w, h)Makes a block of pixels from a Python list of numbers

Saving and resetting

Explained in 2D functions.

NameWhat it does
ctx.save()Remembers every setting on this page, the transform and the clip
ctx.restore()Goes back to the last save()
ctx.reset()Clears the canvas and puts every setting back to the start, including the preview's …

3D: three.js

three.js is there as THREE, and its orbit controls as addons.OrbitControls.

Renderer

Explained in 3D functions.

NameWhat it does
renderer = THREE.WebGLRenderer(canvas=canvas, antialias=True)Makes a renderer that draws on the preview, with smooth edges
renderer.setPixelRatio(pixel_ratio)Sharp on high-resolution screens
renderer.setSize(width, height, False)Fits the preview
renderer.render(scene, camera)Draws one picture; call it in draw()
renderer.setClearColor("navy", 1)The colour behind the scene when it has no background; the second number is how solid
renderer.shadowMap.enabled = TrueTurns shadows on
renderer.shadowMap.type = THREE.PCFSoftShadowMapSoft-edged shadows
renderer.toneMapping = THREE.ACESFilmicToneMappingSoftens very bright light the way a film camera does
renderer.toneMappingExposure = 1.2Overall brightness when tone mapping is on
renderer.outputColorSpace = THREE.SRGBColorSpaceHow colours are sent to the screen

Scene and fog

Explained in 3D functions.

NameWhat it does
scene = THREE.Scene()The world everything goes in
scene.add(thing), scene.remove(thing)Puts something in the world, or takes it out
scene.background = THREE.Color("skyblue")The colour behind everything
scene.fog = THREE.Fog("white", near, far)Fog that starts at distance near and hides everything by far
scene.fog = THREE.FogExp2("white", 0.05)Fog that thickens steadily with distance; the number is how thick

Cameras

Explained in 3D functions.

NameWhat it does
THREE.PerspectiveCamera(fov, width / height, near, far)A camera that sees the way eyes do: far things look smaller
THREE.OrthographicCamera(left, right, top, bottom, near, far)A camera with no perspective: far things look the same size
camera.position.set(x, y, z)Where the camera is
camera.lookAt(x, y, z)Points it at a spot
camera.fov = 30, camera.near, camera.far, camera.zoom = 2Change its settings; follow with camera.updateProjectionMatrix()
camera.updateProjectionMatrix()Applies changed camera settings

Geometries: boxes, spheres, cylinders and every other shape

Explained in 3D functions.

NameWhat it does
THREE.BoxGeometry(w, h, d)A box
THREE.SphereGeometry(radius, 32, 16)A ball
THREE.PlaneGeometry(w, h)A flat rectangle, facing you
THREE.CircleGeometry(radius, 32)A flat disc
THREE.RingGeometry(inner, outer, 32)A flat ring, like a washer
THREE.CylinderGeometry(top_radius, bottom_radius, height, 32)A cylinder; different radii make a tapered tube
THREE.ConeGeometry(radius, height, 32)A cone
THREE.CapsuleGeometry(radius, length, 8, 16)A pill
THREE.TorusGeometry(radius, tube, 16, 64)A ring doughnut
THREE.TorusKnotGeometry(radius, tube, 128, 16)A knotted tube
THREE.TetrahedronGeometry(radius)4 faces
THREE.OctahedronGeometry(radius)8 faces
THREE.DodecahedronGeometry(radius)12 faces
THREE.IcosahedronGeometry(radius, detail)20 faces; raise detail to make it rounder
THREE.LatheGeometry(points, 32)Spins a side outline (a list of THREE.Vector2) round the up axis, like a vase on a potter's …
THREE.ExtrudeGeometry(shape, depth=0.5, bevelEnabled=False)Pushes a flat THREE.Shape out into a solid, like a cookie cutter
THREE.TubeGeometry(curve, 64, radius, 8, False)A tube along a curve, such as THREE.CatmullRomCurve3([...points])
THREE.EdgesGeometry(geometry)Just the edges of another shape, for LineSegments
THREE.WireframeGeometry(geometry)Every triangle's edges, for LineSegments
THREE.BufferGeometry()Your own shape from numbers: geometry.setAttribute("position" …

Materials: how surfaces look, from matte to metal, glass, toon and wireframe

Explained in 3D functions.

NameWhat it does
THREE.MeshBasicMaterial(color=…)Flat colour, ignores light, always visible
THREE.MeshLambertMaterial(color=…)Matte, like chalk or paper
THREE.MeshPhongMaterial(color=…, shininess=80, specular="white")Shiny highlights, like plastic
THREE.MeshStandardMaterial(color=…, roughness=0.5, metalness=0)Realistic
THREE.MeshPhysicalMaterial(color=…, clearcoat=1, transmission=0.9, thickness=0.5)Standard, plus extras: clearcoat (a varnish layer), transmission (glass that lets light …
THREE.MeshToonMaterial(color=…)Cartoon shading in a few flat bands
THREE.MeshNormalMaterial()Rainbow colours by which way each face points; needs no light
THREE.MeshDepthMaterial()White near the camera, fading to black far away
THREE.LineBasicMaterial(color=…)For lines (Line, LineSegments, LineLoop)
THREE.LineDashedMaterial(color=…, dashSize=0.2, gapSize=0.1)Dashed lines; call line.computeLineDistances() once
THREE.PointsMaterial(color=…, size=0.05)For Points
THREE.SpriteMaterial(map=texture)For Sprite, a picture that always faces the camera
color="tomato"The surface colour
emissive="orange", emissiveIntensity=1A glow the surface gives off by itself
map=textureA picture wrapped round the surface
roughness, metalnessStandard and Physical only: rough or polished, metal or not
wireframe=TrueDraws the edges of every triangle only
flatShading=TrueShows the flat faces rather than smoothing over them
side=THREE.DoubleSideShows both sides of flat shapes (FrontSide is the default, BackSide the inside)
transparent=True, opacity=0.5See-through; opacity does nothing without transparent

Lights

Explained in 3D functions.

NameWhat it does
THREE.AmbientLight(colour, intensity)A little light everywhere, from no direction
THREE.HemisphereLight(sky, ground, intensity)Sky colour from above, ground colour from below
THREE.DirectionalLight(colour, intensity)The sun: parallel light from position towards target (the middle unless you move it)
THREE.PointLight(colour, intensity, distance, decay)A bulb: light in every direction from one spot
THREE.SpotLight(colour, intensity, distance, angle, penumbra, decay)A torch: a cone of light from position towards target
THREE.RectAreaLight(colour, intensity, w, h)A glowing panel, like a window or a softbox
light.intensity = 2Brightness
light.color.set("orange")Colour
light.position.set(x, y, z)Where it is
light.target.position.set(x, y, z)Where directional and spot lights point; also scene.add(light.target)
light.visible = FalseSwitches it off
light.castShadow = TrueDirectional, point and spot lights can cast shadows (turn on renderer.shadowMap.enabled and …
light.shadow.mapSize.width = 2048 (and .height)Sharper shadows, at a cost in speed
light.shadow.bias = -0.0005Removes stripy marks on surfaces that shadow themselves
light.shadow.radius = 4Blurs shadow edges (with PCFSoftShadowMap off, PCFShadowMap on)
light.shadow.camera.left / right / top / bottomHow big an area a directional light's shadows cover

Objects

Explained in 3D functions.

NameWhat it does
THREE.Mesh(geometry, material)A solid object
THREE.Group()An empty holder: things added to it move, turn and scale with it
THREE.Points(geometry, THREE.PointsMaterial(size=0.05))A dot at every position in the geometry
THREE.Line(geometry, material)A line through the positions, in order
THREE.LineLoop(geometry, material)The same, joined back to the start
THREE.LineSegments(geometry, material)Separate lines, one for each pair of positions
THREE.Sprite(THREE.SpriteMaterial(map=texture))A flat picture that always faces the camera, for labels and particles
THREE.InstancedMesh(geometry, material, count)Many copies of one mesh drawn at once, much faster than many meshes

Moving and arranging

Explained in 3D functions.

NameWhat it does
thing.position.set(x, y, z), thing.position.x = 2Where it is
thing.rotation.set(x, y, z), thing.rotation.y += 0.01How it is turned round each axis, in radians
thing.scale.set(2, 1, 1), thing.scale.setScalar(2)How big it is along each axis
thing.lookAt(x, y, z)Turns it to face a spot
thing.add(other), thing.remove(other)Puts other inside thing, so it moves with it
thing.visible = FalseHides it
thing.name = "door"A name, handy when picking
thing.castShadow, thing.receiveShadowWhether it makes shadows and shows them

Textures

Explained in 3D functions.

NameWhat it does
THREE.TextureLoader().load(address)Loads a picture from a web address
THREE.CanvasTexture(a_canvas)Uses a 2D canvas you drew on as the picture: text, patterns, anything from 2D functions
texture.needsUpdate = TrueAfter you draw on that canvas again, shows the change
texture.wrapS = texture.wrapT = THREE.RepeatWrappingLets the picture repeat across and down (write it as two lines in Python)
texture.repeat.set(4, 4)How many times it repeats
texture.colorSpace = THREE.SRGBColorSpaceShows a photo's colours correctly
texture.magFilter = THREE.NearestFilterKeeps pixel-art textures blocky

Helpers

Explained in 3D functions.

NameWhat it does
THREE.GridHelper(size, divisions)A grid on the floor
THREE.AxesHelper(length)The three axes: x red, y green, z blue
THREE.DirectionalLightHelper(light, size)Where a directional light is and which way it points
THREE.PointLightHelper(light, size)Where a point light is
THREE.SpotLightHelper(light)A spot light's cone
THREE.HemisphereLightHelper(light, size)A hemisphere light
THREE.CameraHelper(light.shadow.camera)The box a light's shadows cover
THREE.BoxHelper(thing, "yellow")A box round an object

Maths

Explained in 3D functions.

NameWhat it does
THREE.Vector3(x, y, z)A position or direction in 3D
THREE.Vector2(x, y)The same in 2D
THREE.Color(…)A colour
THREE.Euler(x, y, z)A turn round each axis, in radians: what rotation is
THREE.Quaternion()Another way to store a turn, which never gets stuck
THREE.Matrix4()Position, turn and size in one; used by InstancedMesh
THREE.MathUtils.degToRad(90)Degrees to radians; in Python, math.radians(90) does the same and needs no answer back

Picking and controls

Explained in 3D functions.

NameWhat it does
ray = THREE.Raycaster()Makes a picker
ray.setFromCamera(THREE.Vector2(x, y), camera)Aims it through a point, where x and y run from -1 to 1 across and up the preview: x = …
hits = ray.intersectObjects(list_of_things)What it hits, nearest first
controls = addons.OrbitControls(camera, canvas)Drag to orbit, pinch or scroll to zoom, two fingers or right-drag to pan
controls.update()Call every frame in draw()
controls.target.set(x, y, z)The point it orbits round
controls.enableDamping = TrueGlides to a stop when you let go
controls.autoRotate = True, controls.autoRotateSpeed = 2Turns slowly by itself
controls.minDistance = 2, controls.maxDistance = 20How close and how far you can zoom
controls.maxPolarAngle = math.pi / 2Stops the camera going below the floor
controls.enableZoom, controls.enablePan, controls.enableRotateSwitch each gesture on or off

Sprites and hit-testing

Moving pictures that can tell when they touch.

NameWhat it doesMore
Sprite(picture, x, y, size=48)A moving picture with x, y, vx, vy, angle, spin, size, visible, update(dt) …2D functions
remove(things, thing)Take a thing out of a list2D functions
sprite.pictureAn emoji or text, an image from load_image, or a function that draws itDrawing in 2D
sprite.x, sprite.yWhere its centre isDrawing in 2D
sprite.vx, sprite.vyIts speed in points per second, used by update(dt)Drawing in 2D
sprite.angleHow far it is turnedDrawing in 2D
sprite.spinHow fast it turns each second, used by update(dt): degrees(180) is half a turn a secondDrawing in 2D
sprite.sizeHow big it is, in points (48 unless you say)Drawing in 2D
sprite.visibleFalse hides itDrawing in 2D
sprite.update(dt)Moves it by its speed and turns it by its spinDrawing in 2D
sprite.draw()Draws it (call this in your draw())Drawing in 2D
sprite.touches(other)True when the two overlapDrawing in 2D
sprite.hit(sprites)The first sprite in the list that it touches, or None when it touches noneDrawing in 2D
sprite.contains(x, y)True when that point is on itDrawing in 2D
sprite.shape"circle" (as it starts) or "box"Drawing in 2D
sprite.radiusThe size of its circleDrawing in 2D
sprite.width, sprite.heightThe size of its boxDrawing in 2D
sprite.wrap()When it has gone off one edge, it comes back on the opposite oneDrawing in 2D
sprite.bounce()Bounces it off the edgesDrawing in 2D
sprite.offscreen()True when all of it is outside the pictureDrawing in 2D
sprite.push(amount)Speeds it up the way it faces: this is an engineDrawing in 2D
sprite.forward(distance)Steps it the way it faces, without changing its speedDrawing in 2D
sprite.limit(speed)Slows it to that speed if it is going fasterDrawing in 2D
sprite.angle_to(other)The angle from it to another sprite, to mouse, or to a point: angle_to(x, y)Drawing in 2D
sprite.distance_to(other)How far it is to another sprite, to mouse, or to a point: distance_to(x, y)Drawing in 2D
Sprite.box(x, y, width, height, colour)A coloured box, tested as a boxDrawing in 2D
Sprite.circle(x, y, size, colour)A coloured circle size across, tested as that circleDrawing in 2D

Keyboard, mouse and touch

What is held now, what went down since the last frame, and functions called when something happens.

Explained in 2D functions.

NameWhat it does
keysThe set of keys held down: "ArrowLeft" in keys
pressed, releasedThe keys that went down, and came up, since the last frame: " " in pressed
mouse.x, mouse.y, mouse.downWhere the pointer or finger is, and whether it is pressed
mouse.button, mouse.insideWhich button is down ("left", "middle", "right" or None), and whether the pointer is …
mouse.dx, mouse.dy, mouse.wheelHow far the pointer moved, and the wheel turned, since the last frame
touchesEvery finger (or pressed mouse button) that is down: each has id, x, y, start_x …
pinch.scale, pinch.change, pinch.x, pinch.yTwo fingers as a zoom: the scale since the pinch began, its change since the last frame, and …

Functions you write

Explained in How a program is shaped.

NameWhat it does
on_key_down(key, code)A key is pressed
on_key_up(key, code)A key is let go
on_key_repeat(key, code)A key that is held down repeats, as it does when you type
on_mouse_down(x, y, button)The mouse button or a finger goes down
on_mouse_move(x, y)The pointer moves
on_mouse_up(x, y, button)The button or finger comes up
on_touch_start(touch)A finger or a mouse button goes down
on_touch_move(touch)A finger that is down moves
on_touch_end(touch, cancelled)A finger comes up
on_wheel(amount)The wheel turns
on_pinch(scale, change)Two fingers move together or apart

Frames and timing

Used with await, in a loop of your own.

NameWhat it doesMore
await frame()Shows this frame and waits for the next2D functions
await flush()Shows what is drawn so far, now, and carries on2D functions
await sleep(seconds)Waits that long2D functions
await vsync()Another name for frame(): waits for the screen's next refreshHow a program is shaped

Saved values

One value under a name, still there the next time.

Explained in Saved values.

NameWhat it doesIn pictures.js
save(name, value)Keeps the value under that namesave
load(name, otherwise)Gives back the value saved under that nameload

Files

A text or JSON file the program writes and reads back. Real files beside the program in the app on an iPhone, iPad or Android device and for a saved program in the desktop app; kept by the browser on the web and in an exported page: where they are kept.

Explained in Files and databases.

NameWhat it doesIn pictures.js
save_text(path, text)Writes a text filesaveText
load_text(path, otherwise)Gives back the text in the fileloadText
save_json(path, value)Writes a value as a JSON file: a number, text, True or False, a list or a dictionarysaveJSON
load_json(path, otherwise)Gives back the value in a JSON fileloadJSON

Databases

Rows in a SQLite database, asked for in SQL. Real files beside the program in the app on an iPhone, iPad or Android device and for a saved program in the desktop app; kept by the browser on the web and in an exported page: where they are kept.

Explained in Files and databases.

NameWhat it doesIn pictures.js
open_database(name)Opens a database, making it if it is newopenDatabase
db.query(sql, values...)Asks a questiondb.query
db.run(sql, values...)Makes a change: create table, insert, update, deletedb.run
db.close()Finishes with the databasedb.close

Sound and music

The names of synths, the sound library. A program that uses them starts with from synths import *. Loaded only by a program that uses one. The microphone and MIDI are not connected in Circuitry's own preview yet, and a Python program that uses these names cannot be exported as a web page yet.

Game sounds

Explained in the synths function index.

NameWhat it does
play_sound(name, volume, pitch=, pan=, length=)Plays a ready-made game sound: "coin", "jump", "laser" …
sound_names()The list of game sounds

Notes and tunes

Explained in the synths function index.

NameWhat it does
play_note(note, length, volume)Plays a note, a list of notes or a chord by name, now
play_notes(notes, step, repeat=, volume=, hold=)Plays a tune written as text or as a list
note(note, length)The next note of a tune written a line at a time: it begins where the last one ended
chord(name, length)The next thing in the line is a chord
rest(length)A silence in the line
with loop_notes():A section of lines that goes round until its stop()
start_lines()Begins every line again from now
note_number(note)A note as a number: "A4" is 69, and 60 is middle C
set_tempo(beats_a_minute)Sets the tempo
beats(n)How many seconds n beats last
beat()Which beat it is now, with its fraction
sound_time()The sound clock, in seconds

Synths

Explained in the synths function index.

NameWhat it does
make_synth(name, settings=)Makes a synth: a ready-made one by name, a changed one, or one from settings alone
synth_names()The list of ready-made synths
setting_names()The list of every setting
main_synth()The synth that playNote and note play
sound_output()All the sound together, for a scope or a meter
lead.play(note, length, volume)A note, a chord, or the synth's own note
lead.start(note)A note that stays
lead.play(note, length, glide=, bend=, slide=, vibrato=)A note whose pitch moves: a slide in, a scoop, a fall, a vibrato
lead.note_on(note, velocity, at=), lead.note_off(note, at=)A key down and up, now or at an exact time on the sound clock
lead.trance_gate = "x.x.xx.x", lead.set_trance_gate(pattern, rate=, …)A trance gate: the sound chopped in a pattern of steps, in time
lead.arp_pattern = "trance"A pattern of its own for every arpeggio of the synth
lead.stop()Lets go of every note, or of the one named
lead.play_notes(notes, step)A tune on this synth
lead.note(…), lead.chord(…), lead.rest(…)This synth's own line
lead.start_line()Begins this synth's line again from now
lead.arp(chord, length, step=, octaves=, gate=, pattern=)A chord as an arpeggio: fast, or with step each note struck in time with the tempo
lead.start_arp(chord, step=, pattern=)An arpeggio that stays
lead.cutoff = 800Any setting, as a property
lead.set(…, glide=)Changes several settings, or slides there
lead.get(name), lead.describe(name)A setting by name, and its range, unit and kind
lead.macro = [ … ]A step macro
lead.samples(), lead.level(), lead.notes()What it is doing now: its wave, how loud, the notes sounding
lead.sample = load_sample(file)A recording for its wave
lead.voice = "robot"A voice changer on everything it plays
lead.record(seconds)Records this synth alone
lead.play_from_midi(), lead.learn(setting), lead.map_midi(number, setting), lead.send_to_midi()MIDI: a keyboard plays it, a knob turns a setting, what it plays is sent out
lead.remove()Finished with it

Chip sounds and arpeggios

Explained in the synths function index.

NameWhat it does
play_arp(chord, length, speed=, order=)A chord played one note at a time, very fast, on one voice
start_arp(chord)One that stays until its stop(); change(chord) moves it to another chord

Samples

Explained in the synths function index.

NameWhat it does
load_sample(file, loop=, note=)A recorded sound from a file, as a synth
make_synth(sample=file, note=)A synth whose wave is a recording
load_samples(files, kit=, crossfade=, release=)Several recordings as one instrument, each playing the keys near its note
lead.samples = files, lead.set_samples(files, …)The same on a synth you made

Your voice

Explained in the synths function index.

NameWhat it does
use_microphone()The microphone, as a synth whose sound comes in
mic.voice = "robot"A voice: robot, chipmunk, monster, cave, telephone, alien, whisper, or "none"
mic.listen(), mic.mute()Hear yourself, and stop
mic.pitch, mic.ring, mic.comb, mic.gain, mic.gateIts own settings, beside every setting a synth has
mic.state, mic.on_ready(fn)"on", or why there is no microphone
voice_names()The list of voices
stop_microphone()Lets the microphone go

Recording

Explained in the synths function index.

NameWhat it does
record_sound(seconds, effects=)Records the microphone
start_recording(max=)Records until stopRecording(), or for 30 seconds
stop_recording()Ends the recording that is being made
record_output(seconds)Records everything the program plays, in stereo
save_sound(take, name)Saves a recording or a sample as a WAV file

Songs

Explained in the synths function index.

NameWhat it does
play_song(file, repeat=, volume=, raw=, patches=)Plays a .mod, an .xm or a song of synths' own
song.mute(channel), song.unmute(), song.solo(channel)Silences a channel, brings them back, hears one alone
song.loop_pattern()Stays on the pattern that is playing; false carries on
song.positionWhere the song is: its state, pattern, row and tempo
song.channel(n).level()One channel's level, and its samples() and notes()
song.channel(n).volume, .pan, .reverb, .echoThe mix: a channel's fader, its place from left to right, and how much of it goes to the reverb …
song.loop(from, to)A part of the song goes round; null (None) runs on
song.replace(edited)An edited song in the place of the one playing
stop_song()Stops the song that is playing

MIDI

Explained in the synths function index.

NameWhat it does
on_midi_note(fn)Calls fn(note, velocity, channel) for each key
on_midi_note_off(fn)Calls fn(note, channel) when a key comes up
on_midi_control(fn)Calls fn(number, value, channel) when a knob, a slider or a pedal moves
on_midi(fn)Calls fn(message) with everything that arrives
on_midi_devices(fn)Calls fn(devices) when the devices are known, and when one comes or goes
midi_devices()inputs, outputs and available, now
use_midi_input(name)Listens to that device alone
use_midi_output(name)Sends to that device
midi_input(), lead.midi_input()What the program, or one synth, listens to, as something a control is tied to: its "device" …
midi_output(), lead.midi_output()The same for what is sent
send_midi_note(note, velocity, length=, channel=)Sends a note, a chord or a list of notes
send_midi_note_off(note)Lets go of a note that was sent to be held
send_midi_control(number, value)Turns a knob on the other device: value is 0 to 1
send_midi_bend(amount)The pitch wheel, -1 to 1
send_midi_program(number)Chooses a sound on the other device
send_midi_clock()Sends the beat, in time with setTempo; false stops it
send_midi(bytes)Any message, as its bytes
receive_midi(message)Hands the program a message as a keyboard would, for trying a scene with none
stop_midi()Stops everything MIDI is doing

Effects and volume

Explained in the synths function index.

NameWhat it does
set_effects(echo_time=, echo_level=, reverb_type=, reverb_size=, reverb_level=, …)Shapes the echo, the reverb (and which kind it is) and the chorus that all synths share
set_volume(volume)How loud everything is
mute_sound()Silence
unmute_sound()Brings the sound back
stop_sound()Stops everything that is sounding or waiting to sound
sound_button(corner)A speaker on the scene that switches its sound off and on
ask_about_sound(title)For a demo: a card that asks "Play with sound" or "Play without sound" before anything is heard
sound_is_on()Whether the scene's sound is switched on
set_sound_buffer("large")How much sound is made at a time, for a page that clicks: "small", "medium", "large" …
sound_buffer()What it is now: frames, delay, thread, underruns and setting

When a sound starts

Explained in the synths function index.

NameWhat it does
after=0.5That long from now: seconds, or a note length by name
at=sound_time() + 2At a time on the sound clock
beat=8On that beat

Dials, sliders and a keyboard

The names of dials: controls on the program, one line each. A program that uses them starts with from pydials import *. A Python program that uses them cannot be exported as a web page yet.

NameWhat it doesMore
dial(label, min, max, start)A dial for a number: speed.valueEvery control
slider(label, min, max, start)The same, as a sliderEvery control
button(label)A button: fire.pressed is true once for each pressEvery control
toggle(label)A switch: trail.onEvery control
select(label, choices)One of a list: level.valueEvery control
rotary(label, choices)A knob that clicks between a few choices: mode.valueEvery control
keyboard(synth)Piano keys that play a synthEvery control
scope(synth)The wave a synth is making, or any number you pushEvery control
spectrum(synth)The frequencies in a sound, as bars, low notes at the leftEvery control
meter(synth)How loud a synth is, or any level from 0 to 1Every control
label(text)Words: made just before some controls, their headingEvery control
with group(title):A plate with a title, and the controls on itEvery control
row(), with column():, with grid(3):A new line; controls one under another; controls in columns that line upEvery control
page(title)A page of controls with a tab; page() ends the pagesEvery control
spacer(), wrap()The room left over; where a line may be splitEvery control
layout(...), room()Where the plates go, how they fit and wrap; the rectangle no control is onEvery control
theme(...)The colours of all the controlsEvery control
number(label, min, max, start), stepper(…)A number box with − and +, which can be typed intoEvery control
text_box(label, text)One line of text to typeEvery control
readout(label, lambda: value)Shows a value or a message, and takes no handEvery control
checkbox(label, on)A box that is tickedEvery control
choose(label, choices), radio(label, choices)One of a few, all in sightEvery control
dropdown(label, choices)One of a long list, which opens over the controlsEvery control
xy_pad(label, target, "across", "up")A square where one finger sets two numbersEvery control
colour_picker(label, colour), color_picker(…)A patch of colour that opens a pickerEvery control
progress(label, value)A bar that fills, from 0 to 1Every control
light(label, on), busy(label)A light, and a ring that goes round while something is happeningEvery control
range_slider(label, min, max, [low, high])A slider with two handlesEvery control
fader(…)A slider that stands uprightEvery control
joystick()A stick for a thumb: stick.x, stick.yEvery control
dpad()A pad of arrows: pad.left, pad.right, pad.up, pad.downEvery control
action_button("A")A round button for a thumbEvery control
envelope(label, target)The shape of a note as a graph whose corners you dragEvery control
step_grid(label, steps, rows)A grid of steps, each on or offEvery control
pads(label, names, target)Pads to hit, several at onceEvery control
pitch_wheel(…), mod_wheel(…), wheel(…)A wheel that rolls back, and ones that stayEvery control
trance_gate(label, target), arp_pattern(label, target)The editors for a synth's trance gate and its arpeggio patternEvery control
steps(label, 16)A lane of steps, for anythingEvery control
drum_seq(label, drums, target)A drum sequencer that plays by itselfEvery control

Sheet music

The names of notation: music written out as notes on a staff, and lit as it plays. A program that uses them starts with from pynotation import *, which brings the sound with it. Loaded only by a program that uses one.

NameWhat it doesMore
show_notes(music, step, title=, key=, …)Writes music out as notes on a staff over the scene: a tune as text, a sheet, a song or plain data. Gives back the page, with play(), follow(…) and play_along()What you can show
make_sheet(key=, time=, tempo=, title=)A sheet to write a note at a time: sheet.add("D4", "quarter"), sheet.rest("quarter")What you can show

Effects

The names of visualfx: glow, trails, a kaleidoscope and ninety more, done by the graphics card to whatever the program draws. A program that uses them starts with from pyvisualfx import *. Loaded only by a program that uses one. Each effect has a picture on its page.

Shapes of the picture

NameWhat it doesMore
kaleidoscopeOne slice of the picture, folded round and roundEffects
mirrorOne half of the picture shown on both sides, or one quarter in all fourEffects
pixelateBig square pixelsEffects
wavesThe picture ripples like a flag in the windEffects
rippleRings spreading from a point, as from a stone dropped in waterEffects
wobbleThe picture wobbles like jelly, or something seen under waterEffects
swirlThe middle of the picture twisted round, like stirred paintEffects
fisheyeA bulge, as through a round lensEffects
tunnelThe picture becomes the walls of a tunnel you are flying downEffects
tileThe picture repeated in rows and columnsEffects
drosteThe picture inside itself, smaller each time, for everEffects
rotozoomThe picture tiled, turning and zooming: an old demo-scene favouriteEffects
hexagonsSix-sided pixels, like a honeycombEffects
glass_tilesSeen through a wall of glass blocksEffects
frostedSeen through frosted glassEffects
heat_hazeThe shimmer of hot air risingEffects
causticsThe net of bright lines that sunlight makes on the floor of a poolEffects
shakeThe whole picture shakesEffects
punchA zoom in towards a pointEffects

Blur and light

NameWhat it doesMore
zoom_blurRushing towards a pointEffects
spin_blurSpinning round a pointEffects
motion_blurMoving fast in one directionEffects
tilt_shiftA band in focus and the rest blurred, which makes a scene look like a tiny modelEffects
light_raysRays of light streaming out from a point, through whatever is brightEffects
streaksLong sideways flares from bright lights, as a film camera makesEffects
soft_focusA soft, dreamy haze over the bright partsEffects
blurOut of focusEffects
glowBright things shine and spread light around themEffects

What was drawn stays

NameWhat it doesMore
smearWhat was drawn is carried away on a slow current, like wet paintEffects
stutterOnly so many new pictures a second: the last one is held between themEffects
trailsWhat was drawn stays and fadesEffects

Colours

NameWhat it doesMore
rgb_splitRed and blue pulled apart, like a cheap lens or a bad signalEffects
hueEvery colour moved round the colour wheelEffects
saturateMore colour, or less: at 0 the picture is greyEffects
brightenBrighter, or darker below 1Effects
contrastLights lighter and darks darkerEffects
invertA negative: every colour swapped for its oppositeEffects
posterizeOnly a few shades of each colour, like a posterEffects
tintSeen through coloured glassEffects
duotoneTwo colours only: one for the dark parts and one for the lightEffects
colour_cycleBrightness becomes a colour from a palette, and the colours move roundEffects
gradient_mapBrightness becomes a colour from a palette, dark to lightEffects
thermalA heat camera: cold is dark blue, hot is yellow and whiteEffects
night_visionGreen, grainy and bright in the dark, like a night-vision scopeEffects
sepiaThe warm brown of an old photographEffects
thresholdTwo colours and nothing between: dark or lightEffects
solarizeThe bright parts turned to their opposite, as in an over-exposed photographEffects
colour_bleedColours smeared sideways, as on old videotapeEffects
rainbow_edgesEvery edge in the picture drawn in rainbow coloursEffects

Screens and old computers

NameWhat it doesMore
scanlinesDark lines across the picture, as on an old screenEffects
crtAn old television: curved glass, lines, and thin stripes of red, green and blueEffects
glitchA broken signal: blocks that jump sideways, a line that tears, a band of snowEffects
lettersThe picture made of marks, as an old terminal would show itEffects
ditherA few colours made to pass for many with a pattern of dots, as old computers didEffects
interlaceEvery other line dark, swapping each frame, like old videoEffects
ledA wall of round lampsEffects

Drawn, printed and painted

NameWhat it doesMore
edgesOnly the outlines, each in its own colourEffects
dotsPrinted in dots, big where the picture is bright, as a comic or a newspaper isEffects
embossPressed into grey metal: only the bumps and hollows showEffects
sharpenCrisper edgesEffects
sketchA pencil drawing on paperEffects
cartoonFlat colours and black outlinesEffects
stained_glassPieces of coloured glass with dark lead between themEffects
crosshatchShaded with crossing pen lines: more lines where it is darkerEffects
oilSmoothed into patches of colour, like oil paintEffects

In front of the picture

NameWhat it doesMore
grainThe fine speckle of filmEffects
vignetteDark corners, which draw the eye to the middleEffects
dustSpecks and scratches, as on old filmEffects
light_leaksWarm light creeping in from the sides, as in an old cameraEffects
rainRain falling in front of the pictureEffects
snowSnow falling in front of the pictureEffects
bokehSoft discs of coloured light drifting by: lamps out of focusEffects
fogDrifting mist, thicker towards the bottomEffects
lightningA flash, now and thenEffects

Backdrops that need no drawing

NameWhat it doesMore
plasmaSlow rolling colourEffects
starfieldFlying through starsEffects
metaballsBlobs that melt into each other when they meet: a lava lampEffects
flowColour that folds and curls like ink in waterEffects
warpA chequered tunnel rushing pastEffects
voronoiSoft coloured cells that slowly shiftEffects
moireTwo sets of rings crossing, making patterns neither has aloneEffects
interferenceWaves from four moving points, crossingEffects
auroraThe northern lights over a night skyEffects
fireFlames rising from the bottom of the pictureEffects
cloudsA sky with drifting cloudsEffects
matrix_rainGreen marks falling in columnsEffects
copper_barsShining bars sliding up and down: a demo-scene classicEffects
checker_floorA chequered floor rushing towards you under a glowing horizonEffects
twisterA twisting four-sided bar, another demo-scene classicEffects

The music, drawn

NameWhat it doesMore
spectrum_barsThe music as bars: low notes at the left, high at the rightEffects
spectrum_ringThe music as bars round a ringEffects
waveform_ringThe sound's own wave, bent into a ringEffects
beat_flashA flash of colour on each beatEffects
bass_shakeThe picture shakes with the bassEffects

Looks, music and the rest

NameWhat it doesMore
look(name), look_names()A ready-made look: several effects at once, by one nameEffects
clear_effects()Takes every effect offEffects
effect_names(), palette_names()The lists of effects and of palettes, for a programEffects
bass(), mids(), highs(), loudness(), pulse()What the music is doing now, each from 0 to 1, for a scene to draw withEffects
react(effect, setting, band, low, high)Ties a setting of an effect to the musicEffects
listen_to(sound)Which sound the effects hear: all of the scene's unless you sayEffects
shader(code, settings=)An effect of your own, in the graphics card's languageEffects
effects_quality(amount)How many pixels the effects work on: fewer is quickerEffects

Other names

NameWhat it doesMore
measure(name)Times a part of a frame: with measure("physics"):, shown with the frame rateDebugging
EventWhat a JavaScript event listener is handed: canvas.addEventListener("click", on_click)How a program is shaped

Image processing

Methods of a picture from load_image, each used with await: small = await img.resize(width=200). They are part of Circuitry, not of the Pyctures library, so they do not work in an exported page or with pyctures run. Some run on any device and some need an Apple device: the badges say which, and Images from Code has every keyword.

Explained in Images from Code. All of them are In Circuitry only; the badge on each row says which devices.

NameWhat it doesWhere it works
remove_background()Cut out the main subject; everything else becomes transparentApple devicesiOS 17 / macOS 14 or later
resize(width=None, height=None, percent=None, fit="contain")Scale itAny device
enhance()Improve exposure, colour and contrast automaticallyApple devices
sepia(intensity=0.8)Warm brown old-photo toneApple devices
mono()Black and whiteApple devices
noir()High-contrast black and whiteApple devices
vintage()Faded, warm film lookApple devices
blur(radius=10)Soften the whole pictureApple devices
sharpen(radius=2.5, intensity=0.5)Crisper edgesApple devices
vibrance(amount=1)Richer colours, gentlyApple devices
rotate(angle=90, background="#00000000")Rotate by 90/180/270 or any arbitrary angleAny device
flip(axis="horizontal")Mirror horizontally, vertically, or bothAny device
crop(x=0, y=0, width=256, height=256)Cut a rectangular region from an imageAny device
convert(format="webp", quality=0.9)Re-encode as PNG / JPG / WebP / AVIF / HEICAny device
strip_metadata(keep_orientation=True)Remove EXIF / GPS / camera info by re-encodingAny device
edge_detect(kernel="sobel", threshold=80)Sobel / Prewitt / Laplacian edge mapAny device
watermark(text="Sample", anchor="bottom-right", opacity=0.75, font_size=28, color="#ffffff")Write text over the pictureAny device
canny_edges(low=50, high=150)Hysteresis edge detector — cleaner, connected edges vs the kernel filterAny device
threshold(mode="otsu", value=127, invert=False)Binarize via fixed value, Otsu (auto), or local adaptive thresholdingAny device
find_contours(low=50, high=150, min_area=64, overlay=True)Detect blobs/shapes; returns exact count + per-region area, bbox, centroidAny device
detect_shapes(min_area=64, epsilon=0.04, overlay=True)Classify each contour as triangle / rectangle / square / circle / polygonAny device
find_faces(overlay=True)Count the faces in a photo and return where each one isApple devices
read_codes(overlay=True)Read every QR code and barcode in the pictureApple devices
classify(max_labels=10, min_confidence=0.1)Name what is in the picture (dog, beach, food…) with a confidence for each labelApple devices
photo_details()Date taken, location, camera and exposure, as dataApple devices
hide_faces(style="blur")Blur, pixelate or black out every face in the photoApple devices
scan_document(enhance=True)Find the page in a photo and flatten it to a straight-on scanApple devices
smart_crop(aspect="1:1")Crop to the part of the photo that draws the eyeApple devices
straighten()Level a tilted horizonApple devices
favicon_set(include_ico=True, include_manifest=True)Generate web favicons: 16/32/48/192/512 PNGs + apple-touch + favicon.ico + manifest iconsAny device
app_icon_set(platform="ios")Generate iOS .appiconset and/or Android mipmap density buckets with Contents.jsonAny device
trace(colors=16, detail="medium")Turn it into flat-colour vector shapes (as 2Vec does): a Vector you can save as .svg or animate …Any device
save(name)Write the picture beside your .py (.png, .jpg or .webp; a Vector as .svg; a file set as a …Any device
size()The picture's width and height in pixelsAny device
run(name, **keywords)Run any method above by its nameAny device
available()The names of the methods this device can runAny device

Only in Circuitry

Names a Python program has in Circuitry that the Pyctures library does not have on its own. Pymations, for animations that explain, is a library of its own with its own pages.

NameWhat it doesMore
now()The seconds since the program started; while a video is recorded, the video's own timeHow a program is shaped
display(thing)Shows a chart, a table or a picture from another library under the previewCharts and tables
import filesMakes the program's own folder the working folder, for Python's own open()Plain Python files