Skip to content
quickthumb
All documentation

Canvas

The Canvas is the root object. It holds dimensions and an ordered list of layers. Its authoring fields follow the shared layer vocabulary, which also applies to Deck slides and canonical JSON.

Creation

Canvas(width=None, height=None)

from quickthumb import Canvas

canvas = Canvas(1280, 720)
Parameter Type Description
width int \| None Canvas width in pixels. Must be a positive integer.
height int \| None Canvas height in pixels. Must be a positive integer.

Width and height must be given together or both omitted. A canvas built without a size (Canvas()) is unsized: it accepts layer builders but cannot be rendered, diagnosed, or serialized until it gets a size, either directly or by being added to a sized Deck, which gives it the deck's default size. Check canvas.has_size to tell the difference.

Canvas.from_aspect_ratio(ratio, base_width)

Creates a canvas from an aspect ratio string and a base width. Height is calculated automatically.

wide     = Canvas.from_aspect_ratio("16:9", base_width=1280)   # 1280×720
square   = Canvas.from_aspect_ratio("1:1",  base_width=1080)   # 1080×1080
vertical = Canvas.from_aspect_ratio("9:16", base_width=1080)   # 1080×1920
Parameter Type Description
ratio str Aspect ratio string in "W:H" format, e.g. "16:9"
base_width int Canvas width in pixels

Layer builders

All builder methods mutate the canvas and return self, enabling method chaining.

Method Description
.background(...) Add a full-canvas background layer
.text(...) Add a text layer
.image(...) Add an overlay image layer
.shape(...) Add a shape layer
.path(...) Draw a filled or stroked path
.svg(...) Add an SVG layer, rasterized at render time
.video(...) Add a video clip to an animated composition
.counter(...) Add an animated number
.group(...) Add an auto-layout group of child layers
.outline(...) Add a canvas border
.chart(...) Add a deterministic bar or line chart layer from a typed chart spec
.qr_code(...) Add a square QR code layer
.custom(fn) Add a Pillow callback layer

See the data visualization reference and the other individual reference pages for full parameter details.

Animated counters

Use .counter(from_, to, duration, ...) to animate a number as a text layer. Pass normal text options such as position, size, and color:

from quickthumb import Canvas

canvas = Canvas(320, 180).background(color="#102030").counter(
    0, 100, 2, suffix="%", size=64, color="#FFFFFF", position=(40, 50)
)
canvas.render("counter.gif")

delay, decimals, minimum_integer_digits, prefix, suffix, and grouping control timing and formatting. style accepts "plain", "odometer", or "flip"; easing accepts "linear", "ease_in", "ease_out", or "ease_in_out". Static output shows the settled value.

.diagnose()

Checks the composition for layout and legibility issues without writing a file. Returns a DiagnosticReport whose findings list contains Diagnostic entries (empty when clean):

for finding in canvas.diagnose().findings:
    print(finding.severity, finding.code, finding.message)

Finding codes: off-canvas, tiny-text, text-overflow, text-clipped, missing-glyph, low-contrast, layer-overlap, layer-hidden, and edge-crowding. See Diagnostics & CLI for details and the quickthumb lint (or quickthumb diagnose) equivalent.

.prefetch_assets() (optional)

You never need to call this: render() and export() download remote images, SVGs, text fills, and fonts themselves, and export() returns the resulting asset_manifest. Call it only to do those downloads up front, to catch a network failure or a stale cache entry before a long export, or to warm the cache for later offline renders. It returns the manifest without rendering:

manifest = canvas.prefetch_assets().asset_manifest
if any(entry.status == "stale" for entry in manifest):
    ...  # decide whether to proceed with cached bytes

See Remote assets and caching for statuses, QUICKTHUMB_ASSET_MAX_AGE, and offline mode.

Export methods

.export(path, policy=None, *, format=None, quality=None, animation=None)

Writes the canvas like render() and returns an ExportResult whose written_paths lists the single written file. The path may be a string or pathlib.Path; format, quality, animation, and policy mean the same as in render().

result = canvas.export("card.png")
print(result.written_paths)

See Recommended output API for the result fields, the capability preflight, and how export() relates to the methods below.

.render(path, format=None, quality=None, debug=False, animation=None, policy=None)

Renders the canvas and writes the result to a file. The format is detected from the file extension; .svg, .pptx, and .pdf produce vector/document output, and .gif/.mp4/.webm/.mov produce an animation playing the canvas's layer animation effects (see Exporting to SVG, PPTX, PDF & video). Canvas .lot output writes the bounded native-vector subset described in Lottie vectors, using LottieOptions for fps and final hold. Unsupported content is rejected before writing, without PNG fallback.

from quickthumb import GifOptions, VideoOptions

canvas.render("output.png")
canvas.render("output.jpg", format="JPEG", quality=85)
canvas.render("output.webp", format="WEBP", quality=90)
canvas.render("debug.png", debug=True)  # raster output with public layer-id bboxes
canvas.render("output.svg")
canvas.render("output.pptx")  # requires quickthumb[pptx]
canvas.render("output.pdf")   # requires quickthumb[pdf]
canvas.render("output.gif")   # animated; .mp4/.webm/.mov require the ffmpeg binary
canvas.render(
    "preview.gif",
    animation=GifOptions(fps=8, max_size=(540, 960), colors=128),
)
canvas.render("preview.mp4", animation=VideoOptions(fps=30))
Parameter Type Default Description
path str — Output file path
format str \| None None Case-insensitive raster encoding override: "PNG", "JPEG", or "WEBP"; rejected with document/animated extensions.
quality int \| None None Compression quality: JPEG 1–95, WebP 1–100; other targets reject it.
debug bool False Draw public layer-id bounding boxes on raster output for visual review.
animation GifOptions \| VideoOptions \| LottieOptions \| None None Format-specific options: GifOptions for GIF, VideoOptions for MP4/WebM/MOV, LottieOptions for .lot.
policy ExportPolicy \| None None Renderer policy, such as reduced_motion for animated, HTML, and PPTX output. Both render() and export() enforce unsupported_motion before writing. export() reports an explicitly requested static SVG fidelity check.

Warning

Passing quality with format="PNG" raises RenderingError. Passing debug=True for document or animated output (.svg, .pptx, .pdf, .html, .gif, .mp4, .webm, .mov, or .lot) raises RenderingError.

GifOptions, VideoOptions and LottieOptions are available from quickthumb. GifOptions accepts fps, hold, matte, loop, max_size=(width, height), and colors. VideoOptions accepts fps, hold, matte, soundtrack=AudioTrack(...), and loop_audio. VideoOptions(transparent=True) preserves alpha in VP9 WebM or ProRes 4444 MOV (strict boolean, default False); all other output targets reject this option. Both use a strict finite nonnegative hold (default 3 seconds), omitted from serialized options when equal to its default. Both accept workers (a strict integer from 1 to 8, default 1) and render_quality="standard" or "high" for rendering. See parallel animated rendering for spawn setup and supported inputs. GIF sizing and palette controls are rejected for MP4/WebM/MOV output.

.to_svg(embed_fonts=False)

Returns the canvas as an SVG document string. Set embed_fonts=True to inline the used font files as @font-face data URLs.

svg = canvas.to_svg(embed_fonts=True)

.to_pptx()

Returns the canvas as PowerPoint file bytes: a single slide with editable text boxes and autoshapes. Requires the pptx extra.

with open("deck.pptx", "wb") as f:
    f.write(canvas.to_pptx())

.to_pdf()

Returns the canvas as PDF file bytes: a single page with native vector backgrounds, shapes, and selectable text when its font can be safely embedded and the text does not require complex shaping. Unsupported text is embedded as a pixel-exact image fragment. Requires the pdf extra.

with open("card.pdf", "wb") as f:
    f.write(canvas.to_pdf())

.to_gif(...) / .to_mp4(...) / .to_webm(...) / .to_mov(...)

Return the canvas as an animation that plays its layer animation effects in sequence, then holds the settled composition for hold seconds (see Animated GIF & video). A canvas with no animations yields a single-frame GIF. .to_mp4()/.to_webm()/.to_mov() require the ffmpeg binary on PATH (or named by QUICKTHUMB_FFMPEG).

gif_bytes = canvas.to_gif(fps=20, hold=3.0, loop=0, matte="#000000")
mp4_bytes = canvas.to_mp4(fps=30, hold=2.0, soundtrack="music.mp3")
webm_bytes = canvas.to_webm(fps=30, hold=2.0)
overlay_bytes = canvas.to_webm(fps=30, hold=2.0, transparent=True)

.to_mp4()/.to_webm()/.to_mov() also accept soundtrack (an audio file muxed into the video, trimmed to the video length) and loop_audio (an explicit override). AudioTrack(..., loop=True) repeats a shorter configured track; legacy string paths keep the previous default of looping. GIF cannot carry audio. See the Deck API for the full parameter table.

All animated byte methods accept keyword-only workers=1 and render_quality="standard" ("high" enables supersampling). .to_gif() also accepts max_size=None for proportional resizing and colors=None for the palette size (2–256 when supplied). Existing positional parameters remain unchanged.

The keyword-only transparent flag on .to_webm() and .to_mov() skips only the export matte; authored backgrounds stay visible. See transparent WebM for codec, alpha decoding and transition details.

.to_mov() uses the same parameters and timing as .to_webm(), with fixed ProRes 4444 video and AAC audio. It retains odd and one-pixel dimensions. The RGBA source remains 8-bit; 16-bit alpha coding can decode with one-level 8-bit alpha differences, and color is lossy 4:4:4 YUV. See ProRes MOV for the measured conversion limits and encoder requirements. render() and export() accept .mov with VideoOptions for both opaque and transparent output.

.export_image_sequence(output_directory, *, format="png", quality=None, matte=None, lossless=None, options=None, policy=None)

Write the animated timeline as independent PNG (default), JPEG or WebP files plus manifest.json into a new directory under an existing parent. ImageSequenceOptions(fps=30, hold=3, workers=1, render_quality="standard") controls timing/compositing; method keywords select image encoding. JPEG uses RGB on an opaque matte (white by default), with quality=1..95. WebP preserves alpha and accepts lossless=True; lossy WebP accepts quality. PNG and lossless WebP preserve the renderer's exact RGBA8 pixels. Opaque WebP files may decode as RGB; manifest mode describes logical RGBA decoding. The receipt reports actual frame count, timing, encoding and destination. See image sequences for validation, per-format metadata and atomic no-overwrite publication.

.to_base64(format="PNG", quality=None)

Returns the rendered image as a base64-encoded string.

b64 = canvas.to_base64(format="PNG")
b64 = canvas.to_base64(format="WEBP", quality=90)
Parameter Type Default Description
format str "PNG" Output format: "PNG", "JPEG", or "WEBP"
quality int \| None None Compression quality: JPEG 1–95 or WebP 1–100.

.to_data_url(format="PNG", quality=None)

Returns the rendered image as a data URL (data:<mime>;base64,...).

url = canvas.to_data_url(format="JPEG", quality=90)
# → "data:image/jpeg;base64,..."
Parameter Type Default Description
format str "PNG" Output format: "PNG", "JPEG", or "WEBP"
quality int \| None None Compression quality: JPEG 1–95 or WebP 1–100.

.inspect()

Returns a deterministic CanvasInspection containing layer identities, order, visibility, bounding boxes and authored text-layout metadata. No output file is written. Existing font/image assets may be read for sizing, but parent-layer drawing is not invoked.

report = canvas.inspect()
for layer in report.layers:
    print(layer.id, layer.bbox)

For parent-linked scenes, bounds reflect the authored static layout, not a frame of animation; they may conservatively extend beyond painted pixels. Use canvas.render("debug.png", debug=True) to see these boxes. For clips, masks, counters, and parent transforms, see inspecting complex layouts.

.to_json()

Serializes the canvas to a JSON string.

json_str = canvas.to_json()

Raises ValidationError if the canvas contains .custom(fn) layers (callbacks cannot be serialized).

Canvas.from_json(json_str)

Deserializes a canvas from a JSON string.

canvas = Canvas.from_json(json_str)

Note

from_json() expects a JSON string, not a Python dict. Use json.dumps(data) first if you have a dict.

.custom(fn)

Adds a callback that receives and returns a Pillow Image.

from PIL import ImageDraw
from quickthumb import Canvas

def draw_badge(image):
    d = ImageDraw.Draw(image)
    d.polygon([(70, 70), (240, 70), (155, 180)], fill="#FF3B30")
    return image

canvas = Canvas(512, 512).custom(draw_badge)
Rule Detail
fn must be callable Receives a PIL.Image.Image
Return value May return the same image (mutated), a new image of the same size, or None
Errors Exceptions from the callback are wrapped as RenderingError
Serialization Custom layers are not JSON-serializable