Skip to main content

coloX ThorVG Lua Binding Guide

ThorVG-based vector graphics Lua API, using objects and factory functions.

Enabling the Module​

Requires version>=13. Enable vg with usemod('vg'); true indicates success.

usemod('vg')

Three Core Types​

  • canvas — Owns a pixel buffer and handles rendering and output
  • paint — Independently created drawing object, manually added to a canvas
  • font — Font object; retain a reference after loading, released by GC or close()

Core Approach​

Paint objects are created independently of canvases. Add them with canvas:add(paint) to control when and to which canvas they are attached.

local c = vg_new(200, 200)             -- Create a canvas
local r = vg_rect(10, 10, 80, 80) -- Create a separate rectangle
r:fill(255, 0, 0):opacity(180) -- Configure with chained calls
c:add(r) -- Add to the canvas
c:draw(0, 0) -- Render

Contents​

  1. Global factory functions
  2. Canvas methods
  3. Common Paint methods
  4. Shape methods
  5. Text methods
  6. Scene methods
  7. Scene effects
  8. Picture methods
  9. Animation methods
  10. Lottie methods
  11. Font methods
  12. Complete API index
  13. Complete example

1. Global Factory Functions​

All paint objects are created independently through global factories, without depending on a canvas.

vg_new(w, h [, option [, SCR, x, y]]) → canvas​

Creates a canvas with its own pixel buffer for managing paints and rendering output.

  • w (integer) — Canvas width (pixels)
  • h (integer) — Canvas height (pixels)
  • option (integer, optional, default 0) — Option bits:
    • bit0=1: smart drawing (redraw changed regions only)
    • bit1=1: disable antialiasing
  • SCR (string, optional) — Use the screen buffer directly: "SPR" (sfx image) or "SCR" (screen). Requires bpp=32, otherwise fails. x, y locate the drawing rectangle, which must not exceed SCR dimensions
local c = vg_new(200, 200)                -- Create a 200x200 canvas
local c2 = vg_new(200, 200, 1) -- Enable smart drawing
local c3 = vg_new(100, 100, 0, "SPR", 20, 30) -- Use the SPR buffer

img_set_flag(c, '+', 8) -- Do not clear before drawing; faster for full-image redraws

vg_rect(x, y, w, h [, rx, ry]) → paint​

Creates a rectangle paint.

  • x, y (number) — Top-left coordinates
  • w, h (number) — Width and height
  • rx, ry (number, optional, default 0) — Corner radii; rx > 0 creates a rounded rectangle
local r1 = vg_rect(10, 20, 100, 50)           -- Plain rectangle
local r2 = vg_rect(0, 0, 80, 80, 10, 10) -- Rounded rectangle

vg_circle(cx, cy, r) → paint​

Creates a circle paint.

  • cx, cy (number) — Center coordinates
  • r (number) — Radius
local c = vg_circle(100, 100, 50)  -- Center (100,100), radius 50

vg_ellipse(cx, cy, rx, ry) → paint​

Creates an ellipse paint.

  • cx, cy (number) — Center coordinates
  • rx, ry (number) — X/Y radii
local e = vg_ellipse(100, 100, 80, 40)  -- Horizontal ellipse

vg_line(x1, y1, x2, y2) → paint​

Creates a line paint.

  • x1, y1 (number) — Starting coordinates
  • x2, y2 (number) — Ending coordinates
local ln = vg_line(0, 0, 200, 200)  -- Diagonal line

vg_poly(points [, closed]) → paint​

Creates a polygon or polyline paint.

  • points (table) — Coordinates {x1, y1, x2, y2, ...} (at least 2 points/4 numbers, otherwise nil; an unmatched final coordinate is ignored for an odd count)
  • closed (boolean, optional) — Close the path: omitted/false gives a polyline, true a polygon
-- Triangle (closed)
local tri = vg_poly({50, 0, 100, 100, 0, 100}, true)
tri:fill(255, 0, 0)
c:add(tri)

-- Polyline (open)
local line = vg_poly({10, 50, 50, 10, 90, 50})
line:stroke(255, 255, 0, 2)
c:add(line)

vg_path() → paint​

Creates an empty path paint. Build custom paths with move_to, line_to, cubic_to, and close_path.

local p = vg_path()
:move_to(10, 50)
:cubic_to(30, 0, 70, 100, 100, 50)
:line_to(150, 50)
:close_path()
p:fill(100, 200, 255):stroke(0, 0, 0, 1)
c:add(p)

vg_text([str, x, y, font, size [, r, g, b]]) → paint​

Creates a text paint. Without arguments it is empty; configure later with set_text and related methods.

  • str, x, y, font, size — Supply all five or none (fewer than 5 creates empty text and ignores supplied values)
  • r, g, b — Color; optional only when the first 5 arguments are all present (default 255)
  • r, g, b (integer, optional, default 255) — Text color
-- Create directly with all parameters
local font = vg_font_load("/res/sans.ttf")
local txt = vg_text("Hello", 10, 50, font, 24, 255, 255, 0)

-- Create empty, then configure step by step
local txt2 = vg_text()
txt2:set_font(font):set_size(24):set_text("World"):set_color(255, 200, 50)

vg_scene() → paint​

Creates a scene container paint, grouping child paints for shared management and transforms.

local scene = vg_scene()
local s1 = vg_rect(0, 0, 50, 50):fill(255, 0, 0)
local s2 = vg_rect(60, 0, 50, 50):fill(0, 0, 255)
scene:scene_add(s1):scene_add(s2)
c:add(scene)

vg_load_picture(path [, w, h]) → paint​

Creates a paint from an image file. Supports SVG, PNG, JPG, and others (WEBP depends on build options).

  • path (string) — Image file path
  • w, h (number, optional, default 0) — Target dimensions (effective only when supplied together and both nonzero; otherwise original size)
local img = vg_load_picture("/res/logo.svg", 100, 100)
c:add(img)

vg_load_picture_data(data [, mime, w, h]) → paint​

Creates a paint from image data in memory.

  • data (string) — Binary image data
  • mime (string, optional, default "") — MIME type, e.g. "image/svg+xml", "image/png"
  • w, h (number, optional, default 0) — Target dimensions (both must be supplied and nonzero)
local img = vg_load_picture_data(svg_data, "image/svg+xml", 100, 100)
c:add(img)

vg_load_picture_raw(data, w, h [, cs]) → paint​

Creates a paint from raw ABGR8888 pixels.

  • data (string) — Raw ABGR8888 pixel data
  • w (integer) — Width
  • h (integer) — Height
  • cs (integer, optional, default 0) — Color space
local img = vg_load_picture_raw(raw_pixels, 64, 64)
c:add(img)

vg_load_picture_img(img [, sx, sy, sw, sh]) → paint​

Creates a paint from an img module object. Converts images returned by img_load and related functions into ThorVG picture paints, usable alongside other paints with transforms, masks, and clipping.

  • img (img userdata) — Image created by img_load / img_loadwebp, etc.
  • sx, sy, sw, sh (integer, optional) — Subregion relative to the image top-left. Omitting all loads the whole image; out-of-bounds regions are clipped; empty rectangles return nil
  • Supports 32bpp and 16bpp img objects; 16bpp expands internally to 32-bit in host color order. 4bpp/1bpp are unsupported (images lack palettes outside the spec context), returning nil
  • Color space follows the canvas (coloX_rgba byte order), requiring no manual setting
usemod('img')
local img = img_load(picdata) -- 32bpp or 16bpp img object
local p = vg_load_picture_img(img) -- Entire image
c:add(p)

-- Load only the top-left 32×32 image region
local p2 = vg_load_picture_img(img, 0, 0, 32, 32)
c:add(p2)

vg_load_anim(key, json, w, h) → paint​

Loads Lottie animation as a paint, supporting controls such as set_frame and anim_info.

  • key (string) — Animation cache identifier; use a unique key for each animation
  • json (string) — Lottie JSON animation data
  • w, h (number, optional) — Render dimensions (effective only if both > 0; otherwise original Lottie dimensions)

JSON data is usually loaded from external files with #blob, or embedded with =[=[...]=].

local anim = vg_load_anim("loading", lottie_json, 200, 200)
anim:set_frame(0)
c:add(anim)
c:draw(0, 0)

vg_font_load(path) → font​

Loads a font from a file.

  • path (string) — Font file path (TTF, OTF, etc.)
local font = vg_font_load("/res/sans.ttf")
-- Release manually when finished, or leave it to GC
font:close()

vg_font_load_data(name, data [, mime]) → font​

Loads a font from memory.

  • name (string) — Font identifier
  • data (string) — Binary font data
  • mime (string, optional, default "") — MIME type
local font = vg_font_load_data("myfont", font_data, "font/ttf")

2. Canvas Methods​

Created by vg_new, a canvas manages paints and renders output.

canvas:draw(x, y [, flag])​

Renders canvas contents at screen coordinates (x, y), automatically calling update + sync internally.

  • x (integer) — Screen X; nil renders without presenting on screen (offscreen rendering)
  • y (integer) — Screen Y coordinate
  • flag (integer, optional, default 0) — Drawing flags
c:draw(10, 20)       -- Render at screen position (10, 20)
c:draw(0, 0, 0) -- With a flag argument
c:draw(nil) -- Render offscreen only, with no screen output

canvas:add(paint) → canvas​

Appends a paint to the canvas, transferring ownership. Subsequent property changes to that paint remain effective.

  • paint (paint) — Paint to add
local r = vg_rect(0, 0, 100, 100)
r:fill(255, 0, 0)
c:add(r)

canvas:insert(paint [, before]) → canvas​

Inserts a paint before before if provided, otherwise appends it. Insertion order determines layers; earlier paints draw first (underneath).

  • paint (paint) — Paint to insert
  • before (paint, optional) — Reference paint; insert the new paint before it
local bg = vg_rect(0, 0, 200, 200):fill(0, 0, 0)
local fg = vg_circle(100, 100, 50):fill(255, 0, 0)

c:add(fg)
c:insert(bg, fg) -- Insert bg before fg as the bottom layer

canvas:remove(paint)​

Removes a paint from the canvas. The object remains alive and can be added to another canvas.

  • paint (paint) — Paint to remove
c:remove(r)

canvas:clear()​

Clears all paints from the canvas.

c:clear()

canvas:close()​

Destroys the canvas and releases pixel buffers and resources. GC also calls this automatically.

c:close()

canvas:viewport(x, y, w, h) → canvas​

Sets the drawing viewport. Only the viewport region is rendered, useful for partial redraw optimization.

  • x (integer) — Viewport top-left X
  • y (integer) — Viewport top-left Y
  • w (integer) — Viewport width
  • h (integer) — Viewport height

Note: Call after canvas:sync(). After changing the viewport, do not call add/remove/update/draw until the next sync.

c:sync()
c:viewport(50, 50, 100, 100) -- Render only the region (50,50)-(150,150)

canvas:update() → canvas​

Triggers a canvas update separately after paint changes and before draw. Usually unnecessary because draw calls update internally. Useful when controlling update/sync/draw separately.

c:update()

canvas:sync() → canvas​

Waits separately for rendering completion. Useful for separating update + draw + sync, e.g. partial redraws with viewport.

-- Control the rendering sequence manually
c:update()
c:sync()
c:viewport(50, 50, 100, 100) -- Set viewport only after sync

canvas:info() → w, h​

Gets canvas dimensions.

Return values:

  • w (integer) — Width
  • h (integer) — Height
local w, h = c:info()
print(string.format("canvas: %dx%d", w, h))

3. Common Paint Methods​

Basic methods shared by Shape / Text / Scene / Picture / Animation paints. All use : syntax and return self for chaining (except duplicate and getters).

p:duplicate() → paint​

Duplicates a paint as a fully independent object, inheriting paths, colors, transforms, and other properties, but not animation state. Useful for creating many similar shapes.

local r = vg_rect(0, 0, 100, 50):fill(255, 0, 0)
local r2 = r:duplicate() -- Independent copy
r2:fill(0, 255, 0):translate(120, 0)
c:add(r)
c:add(r2)

p:translate(x, y) → self​

Translates a paint by the specified X/Y distances.

  • x (number) — X offset
  • y (number) — Y offset

Note: translate is cumulative, composing with the current matrix. Use set_transform for absolute animation matrices to avoid accumulated drift.

r:translate(50, 30)

p:rotate(degrees) → self​

Rotates a paint around the origin by the specified angle.

  • degrees (number) — Rotation in degrees, positive clockwise

Note: rotate is cumulative. To rotate around another point, use set_transform with a transform matrix.

r:rotate(45)

p:scale(factor) → self​

Scales a paint uniformly around the origin.

  • factor (number) — Scale factor: 1.0=original, 2.0=double, 0.5=half

Note: scale is cumulative.

r:scale(1.5)

p:set_transform(e11, e12, e13, e21, e22, e23 [, e31, e32, e33]) → self​

Sets a 3x3 affine transform matrix directly. Two forms:

  • 9 individual numeric arguments: e11, e12, e13, e21, e22, e23, e31, e32, e33
  • 1 table: {e11, e12, e13, e21, e22, e23, e31, e32, e33} (only the first 6 values required; e31=0, e32=0, e33=1 may be omitted; fewer than 6 values is invalid, returning nil)

Matrix layout:

| e11  e12  e13 |
| e21 e22 e23 |
| e31 e32 e33 |

Note: Unlike translate/rotate/scale, set_transform sets absolutely, replacing the current matrix. Recommended for animation.

-- 9 arguments
r:set_transform(1, 0, 50, 0, 1, 30, 0, 0, 1) -- Translation offset (50, 30)

-- Table form (first 6 values; the last 3 default to 0,0,1)
r:set_transform({1, 0, 50, 0, 1, 30})

-- Helper: rotate and scale around (cx,cy)
local function xform(cx, cy, s, angle)
local rad = math.rad(angle)
local c = math.cos(rad)
local si = math.sin(rad)
return {
s * c, -s * si, cx - s * (cx * c - cy * si),
s * si, s * c, cy - s * (cx * si + cy * c)
}
end
r:set_transform(xform(100, 100, 1.5, 45))

p:opacity(v) → self​

Sets opacity.

  • v (integer) — Opacity 0-255; 0=fully transparent, 255=fully opaque
r:opacity(180)

p:visible(bool) → self​

Shows/hides a paint. Hidden paints are not rendered but remain in the canvas.

  • bool (boolean) — true=visible, false=hidden
r:visible(false)  -- Hide
r:visible(true) -- Show

p:blend(method) → self​

Sets the blending mode.

  • method (integer) — Blending mode:
    • 0 = normal
    • 1 = multiply
    • 2 = screen
    • 3 = overlay
    • 16 = add (often used for glow effects)
r:blend(16)  -- Additive blending for glow

p:clip(clipper_paint) → self​

Clips using another paint's shape; only content inside that region is visible.

  • clipper_paint (paint) — Paint defining the clipping region
local clip = vg_circle(100, 100, 50)  -- Circular clipping region
local img = vg_load_picture("/res/bg.jpg", 200, 200)
img:clip(clip)
c:add(img)

p:mask(target, method) → self​

Masks using another paint, combined with the selected method.

  • target (paint) — Mask paint
  • method (integer) — Mask method:
    • 0 = none
    • 1 = alpha
    • 2 = inverse_alpha
    • 3 = luma
    • 4 = inverse_luma
    • 5 = add
    • 6 = subtract
    • 7 = intersect
    • 8 = difference
    • 9 = lighten
    • 10 = darken
local mask = vg_circle(100, 100, 50)
mask:fill(255, 255, 255)
local img = vg_load_picture("/res/bg.jpg", 200, 200)
img:mask(mask, 1) -- Alpha mask
c:add(img)

p:get_opacity() → opacity​

Gets current opacity.

Return values:

  • opacity (integer) — Opacity, 0-255
local op = r:get_opacity()

p:get_visible() → bool​

Gets current visibility.

Return values:

  • bool (boolean) — Visibility
local vis = r:get_visible()

p:get_transform() → e11, e12, e13, e21, e22, e23, e31, e32, e33​

Gets the current transform matrix.

Returns 9 numbers, the components of the 3x3 matrix.

local e11, e12, e13, e21, e22, e23, e31, e32, e33 = r:get_transform()

p:get_type() → type​

Gets paint type.

Return values:

  • type (integer) — Type: 0=undef, 1=shape, 2=scene, 3=picture, 4=text
local t = r:get_type()
if t == 1 then print("shape") end

p:get_aabb() → x, y, w, h​

Gets the axis-aligned bounding box (AABB).

Return values:

  • x, y (number) — Bounding box top-left coordinates
  • w, h (number) — Bounding box dimensions
local x, y, w, h = r:get_aabb()
print(string.format("AABB: (%.1f,%.1f) %.1fx%.1f", x, y, w, h))

p:get_obb() → {{x,y}, {x,y}, {x,y}, {x,y}}​

Gets the oriented bounding box (OBB), including transforms such as rotation, as four corners.

Returns a table of 4 points, each {x, y}.

local corners = r:get_obb()
for i, pt in ipairs(corners) do
print(i, pt[1], pt[2])
end

p:intersects(x, y [, w, h]) → bool​

Tests whether a rectangle intersects the paint region.

  • x, y (integer) — Test region top-left
  • w, h (integer, optional, default 1) — Test dimensions; omitted means a point test

Return values:

  • bool (boolean) — Whether they intersect
if r:intersects(50, 50) then       -- Point test
print("hit!")
end
if r:intersects(0, 0, 100, 100) then -- Rectangle test
print("overlap!")
end

p:get_clip() → paint | nil​

Gets the current clipping paint.

Return values:

  • paint (paint) — Clipping object, or nil if unset
local clipper = r:get_clip()

p:get_parent() → paint | nil​

Gets the parent paint; returns the scene if added to a scene.

Return values:

  • paint (paint) — Parent, or nil if none
local parent = r:get_parent()

p:set_id(id) → self​

Sets a unique paint ID, identifying it for advanced capabilities such as accessor.

  • id (integer) — Unique identifier
r:set_id(1001)

p:get_id() → id​

Gets paint ID.

Return values:

  • id (integer) — Paint ID
local id = r:get_id()

p:set_accessible(bool) → self​

Enables/disables Picture accessible mode. When enabled, it maintains an internal ID-name mapping for accessing named elements through accessor. Picture only.

  • bool (boolean) — true enables, false disables
local pic = vg_load_picture("icon.svg")
pic:set_accessible(true)

p:accessor(func) → self​

Recursively traverses descendants, calling Lua for each node. Applies to any paint type (Picture, Scene, Shape, Text).

Callback signature: func(ptype, pid, getobj)

Parameters:

  • ptype (integer) — Paint type: 0=undef, 1=shape, 2=scene, 3=picture, 4=text
  • pid (integer) — Paint ID (from set_id or original SVG/Lottie ID)
  • getobj (function) — Call on demand to obtain the paint. Userdata creation and ref happen only when called, avoiding unnecessary overhead

Return values:

  • true — Continue traversal
  • false — Stop traversal

Performance: ptype and pid are lightweight numbers creating no objects. Call getobj() only when manipulation is needed. To retain a paint reference, store the result of getobj() in a variable/table; GC releases it automatically.

-- Lightweight iteration: inspect type and ID without creating paint objects
local anim = vg_load_anim("test", json_data, 200, 200)
anim:accessor(function(ptype, pid, getobj)
print("type:", ptype, "id:", pid)
return true
end)

-- Filter and retain references to specific paints
local layers = {}
anim:accessor(function(ptype, pid, getobj)
if ptype == 2 and pid ~= 0 then -- Scene with an ID
local child = getobj() -- Get the paint object on demand
table.insert(layers, child) -- Retain the reference
end
return true
end)

-- Work with the retrieved paint
for i, layer in ipairs(layers) do
print("layer:", layer:get_type(), layer:get_id())
layer:opacity(128)
end

4. Shape Methods​

Shape is the most common paint type, created by vg_rect, vg_circle, vg_ellipse, vg_line, vg_poly, and vg_path. Provides path construction, fill/stroke, shape properties, and gradient methods.

p:move_to(x, y) → self​

Moves the pen to a position, starting a new segment in an empty vg_path().

  • x, y (number) — Destination coordinates
local p = vg_path()
p:move_to(10, 50) -- Move the pen to (10, 50)

p:line_to(x, y) → self​

Draws a straight line from the current position to the specified point.

  • x, y (number) — Ending coordinates
p:line_to(100, 50)  -- Draw a line to (100, 50)

p:cubic_to(cx1, cy1, cx2, cy2, x, y) → self​

Draws a cubic Bezier from the current position through two control points to the endpoint.

  • cx1, cy1 (number) — First control point
  • cx2, cy2 (number) — Second control point
  • x, y (number) — Endpoint
-- Draw a Bezier curve from the current position
p:cubic_to(30, 0, 70, 100, 100, 50)

p:close_path() → self​

Closes the path with a line from the current point to its start, forming a closed region.

p:close_path()

p:fill(r, g, b [, a]) → self​

Sets fill color.

  • r, g, b (integer) — RGB components, 0-255
  • a (integer, optional, default 255) — Alpha opacity, 0-255
r:fill(255, 0, 0)        -- Opaque red
r:fill(0, 255, 0, 128) -- Semitransparent green

p:stroke(r, g, b, width) → self​

Sets stroke color and width.

  • r, g, b (integer) — RGB components, 0-255
  • width (number) — Stroke width (pixels)
r:stroke(0, 0, 0, 2)  -- Black stroke, width 2

p:stroke_width(width) → self​

Sets stroke width without changing color.

  • width (number) — Stroke width
r:stroke_width(3.5)

p:stroke_dash({len1, len2, ...}) → self​

Sets alternating dash/gap lengths.

  • pattern (table) — Dash array {dash length, gap length, ...}
line:stroke_dash({10, 5})          -- 10 pixels on, 5 pixels off
line:stroke_dash({10, 5, 2, 5}) -- Compound dash pattern

p:stroke_cap(cap) → self​

Sets stroke cap style.

  • cap (integer) — Cap type:
    • 0 = butt
    • 1 = round
    • 2 = square (extends half the stroke width beyond endpoints, default)
line:stroke_cap(1)  -- Round caps

p:stroke_join(join) → self​

Sets stroke join style.

  • join (integer) — Join type:
    • 0 = miter
    • 1 = round
    • 2 = bevel (default)
line:stroke_join(1)  -- Round joins

p:stroke_miterlimit(limit) → self​

Sets the miter limit; excessively sharp joins fall back to bevel.

  • limit (number) — Limit, default 4; larger values allow sharper corners
line:stroke_miterlimit(8)

p:fill_rule(rule) → self​

Sets the fill rule.

  • rule (integer) — Fill rule:
    • 0 = non_zero (nonzero winding, default)
    • 1 = even_odd
p:fill_rule(1)  -- Even-odd fill for cutouts

p:paint_order(stroke_first) → self​

Sets fill/stroke drawing order.

  • stroke_first (boolean) — true=stroke then fill; false=fill then stroke (default)
r:paint_order(true)  -- Stroke above the fill

p:trimpath(begin, end [, sim]) → self​

Trims a path to display only part of it, useful for path animation.

  • begin (number) — Starting position, [0, 1]
  • end (number) — Ending position, [0, 1]
  • sim (boolean, optional, false when omitted in Lua) — true: independently trim all subpaths simultaneously; false: trim subpaths by their combined total length
-- Show the first half of the path
p:trimpath(0, 0.5)
-- Path animation: reveal gradually
p:trimpath(0, progress)

p:reset() → self​

Resets path data, clearing all commands (move_to, line_to, etc.) but retaining fill/stroke properties.

p:reset()
p:move_to(0, 0):line_to(100, 100) -- Rebuild the path

p:gradient_linear(x1, y1, x2, y2, stops) → self​

Linear gradient fill: colors transition from (x1,y1) to (x2,y2) along a straight line.

  • x1, y1 (number) — Gradient start
  • x2, y2 (number) — Gradient end
  • stops (table) — Color stops {offset1, r1, g1, b1, a1, offset2, r2, g2, b2, a2, ...}
    • offset ranges [0, 1], specifying gradient position
-- Left-to-right gradient: red to blue
local r = vg_rect(0, 0, 200, 200)
r:gradient_linear(0, 0, 200, 0,
{0, 255,0,0,255, -- offset=0: opaque red
1.0, 0,0,255,255}) -- offset=1: opaque blue
c:add(r)

-- Gradient with multiple color stops
r:gradient_linear(0, 0, 0, 200,
{0, 255,0,0,255, -- Top: red
0.5, 255,255,0,255, -- Middle: yellow
1.0, 0,0,255,255}) -- Bottom: blue

p:gradient_radial(cx, cy, r [, fx, fy, fr], stops) → self​

Radial gradient fill: colors spread outward from the center.

  • cx, cy (number) — Outer circle center
  • r (number) — Outer circle radius
  • fx, fy, fr (number, optional) — Focal position and radius; default focus is the outer circle center
  • stops (table) — Color stops (as in gradient_linear)
-- Simple radial gradient
local circle = vg_circle(100, 100, 50)
circle:gradient_radial(100, 100, 50,
{0, 255,0,0,255, -- Center: red
1.0, 0,0,255,255}) -- Edge: blue

-- Radial gradient with an offset focal point
circle:gradient_radial(100, 100, 50, 80, 80, 10,
{0, 255,255,200,255,
1.0, 100,50,20,255})

p:stroke_gradient(type, ...) → self​

Stroke gradient: same parameters as fill gradients, applied to the stroke instead.

  • type (integer) — Gradient type: 1=linear, 2=radial
  • Remaining arguments match gradient_linear or gradient_radial
-- Linear stroke gradient
local s = vg_rect(10, 10, 80, 80)
s:stroke_gradient(1, 0, 0, 100, 0,
{0, 255,0,0,255,
1.0, 0,0,255,255})

p:gradient_spread(spread) → self​

Sets how a fill gradient extends beyond its bounds when smaller than the paint.

Prerequisite: first set a fill gradient (gradient_linear/gradient_radial), otherwise this and get_gradient_spread return no value. Applies to fill gradients only, not strokes.

  • spread (integer) — Spread mode:
    • 0 = pad (extend edge colors, default)
    • 1 = reflect (reflected repetition)
    • 2 = repeat (tiled repetition)
r:gradient_spread(2)  -- Repeat the pattern

p:get_gradient_spread() → spread​

Gets fill gradient spread mode.

Return values:

  • spread (integer) — 0=pad, 1=reflect, 2=repeat
local spread = r:get_gradient_spread()

p:gradient_transform(e11, e12, e13, e21, e22, e23 [, e31, e32, e33]) → self​

Sets a separate gradient transform for translation/rotation/scaling, without affecting the paint's transform. Same format as set_transform: 9 numbers or 1 table.

Prerequisite: a fill gradient must already exist, otherwise no value is returned. Applies only to fill gradients.

-- Rotate the gradient by 45 degrees
r:gradient_transform(0.707, -0.707, 50, 0.707, 0.707, 50)

-- Use table form
r:gradient_transform({0.707, -0.707, 50, 0.707, 0.707, 50})

p:get_gradient_transform() → e11, e12, e13, e21, e22, e23, e31, e32, e33​

Gets gradient transform matrix.

Returns 9 numbers for the gradient's 3x3 transform matrix.

local e11, e12, e13, e21, e22, e23, e31, e32, e33 = r:get_gradient_transform()

p:get_fill_color() → r, g, b, a​

Gets fill color.

Returns 4 integers: RGBA components (0-255).

local r, g, b, a = shape:get_fill_color()

p:get_fill_rule() → rule​

Gets fill rule.

Return values:

  • rule (integer) — 0=non_zero, 1=even_odd
local rule = shape:get_fill_rule()

p:get_stroke_color() → r, g, b, a​

Gets stroke color.

Returns 4 integers: RGBA components (0-255).

local r, g, b, a = shape:get_stroke_color()

p:get_stroke_width() → width​

Gets stroke width.

Return values:

  • width (number) — Stroke width
local w = shape:get_stroke_width()

p:get_stroke_cap() → cap​

Gets cap style.

Return values:

  • cap (integer) — 0=butt, 1=round, 2=square

p:get_stroke_join() → join​

Gets join style.

Return values:

  • join (integer) — 0=miter, 1=round, 2=bevel

p:get_stroke_miterlimit() → limit​

Gets miter limit.

Return values:

  • limit (number) — Limit

p:get_path() → cmds_table, pts_table​

Gets path commands and corresponding coordinates.

Return values:

  • cmds_table (table) — Path command array
  • pts_table (table) — Coordinate array
local cmds, pts = shape:get_path()

p:get_gradient() → type, params..., stops_table​

Gets fill gradient information.

Return values:

  • type (integer) — Gradient type
  • params... — Gradient parameters (coordinates/radii/etc., depending on type)
  • stops_table (table) — Color stop array

p:get_stroke_dash() → {len,...}, offset​

Gets dash pattern.

Return values:

  • {len,...} (table) — Dash array
  • offset (number) — Dash offset
local pattern, offset = shape:get_stroke_dash()

p:get_stroke_gradient() → type, params..., stops_table​

Gets stroke gradient information, same return format as get_gradient. Both return nil when no gradient is set.


5. Text Methods​

Text paints created by vg_text() provide font, layout, and measurement methods.

-- Method 1: direct creation
local font = vg_font_load("/res/sans.ttf")
local txt = vg_text("Hello", 10, 50, font, 24, 255, 255, 0)
txt:wrap(2):layout(200, 100)
c:add(txt)

-- Method 2: configure step by step
local txt2 = vg_text()
txt2:set_font(font):set_size(24):set_text("Hello World")
txt2:set_color(255, 200, 50):set_italic(0.18)
txt2:set_outline(1.5, 0, 0, 0)
txt2:layout(200, 0):align(0.5, 0.5)
txt2:translate(10, 80)
c:add(txt2)

p:set_font(font) → self​

Sets a font, accepting a font object or font name string.

  • font (font | string) — Font object returned by vg_font_load, or a font name
local font = vg_font_load("/res/sans.ttf")
txt:set_font(font)
-- Or use the font name
txt:set_font("sans")

p:set_size(size) → self​

Sets font size. Floating-point sizes support subpixel-precision rendering.

  • size (number) — Font size (pixels)
txt:set_size(24)
txt:set_size(18.5) -- Subpixel precision

p:set_text(utf8) → self​

Sets text content to render.

  • utf8 (string) — UTF-8 text
txt:set_text("Hello World")
txt:set_text("你好世界") -- Intentional Chinese text for UTF-8 rendering

p:set_color(r, g, b) → self​

Sets text color.

  • r, g, b (integer) — RGB components, 0-255
txt:set_color(255, 200, 50)

p:set_italic(shear) → self​

Sets italic deformation, simulating italics through shear.

  • shear (number) — Shear amount, [0, 0.5]; recommended 0.18
txt:set_italic(0.18)  -- Standard italic

p:set_outline(width, r, g, b) → self​

Sets a text outline.

  • width (number) — Stroke width; 0 disables the outline
  • r, g, b (integer) — Outline color
txt:set_outline(1.5, 0, 0, 0)  -- 1.5-pixel black outline
txt:set_outline(0, 0, 0, 0) -- Disable the outline

p:set_gradient(type, ...) → self​

Sets gradient text fill instead of set_color.

  • type (integer) — Gradient type: 1=linear, 2=radial
  • Remaining arguments:
    • type=1 (linear): set_gradient(1, x1, y1, x2, y2, stops)
    • type=2 (radial): set_gradient(2, cx, cy, r [, fx, fy, fr], stops)
  • stops uses the same format as gradient_linear
txt:set_gradient(1, 0, 0, 200, 0,
{0, 255,0,0,255,
1.0, 0,0,255,255})

p:align(x, y) → self​

Sets text alignment/anchor; use together with layout.

  • x (number) — Horizontal alignment: 0=left, 0.5=center, 1=right
  • y (number) — Vertical alignment: 0=top, 0.5=center, 1=bottom
txt:align(0.5, 0.5)  -- Center alignment
txt:layout(200, 100) -- Use with layout

p:layout(w, h) → self​

Sets layout constraints; text is arranged and wrapped within a virtual box.

  • w (number) — Layout width; 0 means unlimited
  • h (number) — Layout height; 0 means unlimited
txt:layout(200, 0)   -- Limit width, leave height unrestricted
txt:layout(200, 100) -- 200x100 layout box

p:wrap(mode) → self​

Sets wrapping mode.

  • mode (integer) — Wrapping mode:
    • 0 = no wrapping (default)
    • 1 = character wrapping
    • 2 = word wrapping
    • 3 = smart wrapping
    • 4 = ellipsis truncation
txt:wrap(2)   -- Wrap at words
txt:wrap(4) -- Show an ellipsis on overflow

p:spacing(letter, line) → self​

Sets letter and line spacing scale factors.

  • letter (number) — Letter spacing factor, default 1.0; >1 widens, <1 tightens
  • line (number) — Line spacing factor, default 1.0
txt:spacing(1.2, 1.5)  -- Increase character spacing by 20% and line spacing by 50%

p:get_text() → string​

Gets current text.

Return values:

  • string — Text content
local str = txt:get_text()

p:line_count() → number​

Gets wrapped line count; call layout + wrap first.

Return values:

  • number — Line count
local lines = txt:line_count()

p:metrics() → ascent, descent, linegap, advance​

Gets font metrics.

Return values:

  • ascent (number) — Height above baseline
  • descent (number) — Depth below baseline
  • linegap (number) — Line gap
  • advance (number) — Advance distance
local ascent, descent, linegap, advance = txt:metrics()

p:glyph_metrics(ch) → advance, bearing, min_x, min_y, max_x, max_y​

Gets metrics for a single character.

  • ch (string) — Character to query

Returns 6 numbers representing glyph metrics.

local adv, bearing, x0, y0, x1, y1 = txt:glyph_metrics("A")

6. Scene Methods​

Scene paints created by vg_scene() group child paints added through scene_add.

local scene = vg_scene()

local s1 = vg_rect(0, 0, 50, 50):fill(255, 0, 0)
local s2 = vg_rect(60, 0, 50, 50):fill(0, 0, 255)

scene:scene_add(s1):scene_add(s2)

c:add(scene)

p:scene_add(child) → self​

Adds a child to the scene, transferring ownership to the scene.

  • child (paint) — Child paint
scene:scene_add(s1):scene_add(s2)

p:scene_remove([child]) → self​

Removes a child, or clears the entire scene if omitted.

  • child (paint, optional) — Child to remove; omitted clears the scene
scene:scene_remove(s1)  -- Remove one item
scene:scene_remove() -- Clear the scene

p:scene_insert(target [, before]) → self​

Inserts target before before, or appends it if omitted.

  • target (paint) — Paint to insert
  • before (paint, optional) — Reference paint to insert target before
scene:scene_insert(new_paint, existing_paint)  -- Insert before existing
scene:scene_insert(new_paint) -- Append at the end

7. Scene Effects​

Effects apply to Scene paints.

local scene = vg_scene()
local s1 = vg_rect(0, 0, 50, 50):fill(255, 0, 0)
local s2 = vg_rect(60, 0, 50, 50):fill(0, 0, 255)
scene:scene_add(s1):scene_add(s2)
scene:effect_blur(3.0)
c:add(scene)

p:effect_blur(sigma [, dir, border, quality]) → self​

Gaussian blur.

  • sigma (number) — Blur radius (standard deviation); larger is blurrier
  • dir (integer, optional, default 0) — Direction: 0=both, 1=horizontal, 2=vertical
  • border (integer, optional, default 0) — Edge handling: 0=duplicate edge pixels, 1=wrap
  • quality (integer, optional, default 100) — Quality, 0-100
scene:effect_blur(3.0)              -- Blur in both directions
scene:effect_blur(5.0, 1, 0, 80) -- Horizontal blur only

p:effect_shadow(r, g, b, a, angle, dist, sigma [, quality]) → self​

Drop shadow: creates a blurred, offset shadow beneath the content.

  • r, g, b, a (integer) — Shadow color, 0-255
  • angle (number) — Shadow offset angle (degrees)
  • dist (number) — Shadow offset distance
  • sigma (number) — Blur radius
  • quality (integer, optional, default 100) — Quality, 0-100
scene:effect_shadow(0, 0, 0, 128, 90, 3, 2.0)   -- Semitransparent black shadow
scene:effect_shadow(100, 80, 200, 50, 90, 2, 1.5) -- Faint purple shadow

p:effect_fill(r, g, b, a) → self​

Fill effect: overlays scene contents with a solid color, preserving the Alpha silhouette.

  • r, g, b, a (integer) — Fill color, 0-255
scene:effect_fill(255, 0, 0, 128)  -- Semitransparent red overlay

p:effect_tint(br, bg, bb, wr, wg, wb, intensity) → self​

Tint effect: independently maps black and white channels to colors.

  • br, bg, bb (integer) — Black channel color (shadow mapping)
  • wr, wg, wb (integer) — White channel color (highlight mapping)
  • intensity (number) — Tint intensity
scene:effect_tint(50, 0, 80, 200, 180, 255, 0.8)

p:effect_tritone(sr, sg, sb, mr, mg, mb, hr, hg, hb [, blend]) → self​

Tritone effect: separately colors shadows, midtones, and highlights.

  • sr, sg, sb (integer) — Shadow color
  • mr, mg, mb (integer) — Midtone color
  • hr, hg, hb (integer) — Highlight color
  • blend (integer, optional, default 128) — Blending factor
scene:effect_tritone(
0, 0, 50, -- Shadows: dark blue
100, 50, 150, -- Midtones: purple
255, 200, 100, -- Highlights: warm yellow
128) -- Blend factor

p:clear_effects() → self​

Clears all applied effects.

scene:clear_effects()

8. Picture Methods​

Picture paints are created by vg_load_picture, vg_load_picture_data, vg_load_picture_raw, and vg_load_picture_img.

-- Load from a file
local img = vg_load_picture("/res/logo.svg", 100, 100)
c:add(img)

-- Load from memory
local img2 = vg_load_picture_data(data, "image/svg+xml", 100, 100)
c:add(img2)

p:set_size(w, h) → self​

Sets picture display dimensions.

  • w, h (number) — Target dimensions
img:set_size(200, 200)

p:get_size() → w, h​

Gets picture dimensions.

Return values:

  • w (number) — Width
  • h (number) — Height
local w, h = img:get_size()

p:set_origin(x, y) → self​

Sets a normalized origin, the reference point for picture translation, rotation, and scaling.

  • x, y (number) — Normalized coordinates [0, 1]; (0,0)=top-left, (0.5,0.5)=center, (1,1)=bottom-right
img:set_origin(0.5, 0.5)  -- Rotate around the center
img:rotate(45)

p:get_origin() → x, y​

Gets the normalized origin.

Return values:

  • x, y (number) — Normalized coordinates
local ox, oy = img:get_origin()

p:set_filter(method) → self​

Sets picture filtering, determining the sampling algorithm during scaling.

  • method (integer) — Filtering:
    • 0 = bilinear (default; smooth scaling)
    • 1 = nearest (pixel-art style, sharp edges)
img:set_filter(1)  -- Nearest-neighbor filtering for pixel art

Setting Filters on Picture Layers inside Lottie​

set_filter is a Picture method; Lottie Animation paints returned by vg_load_anim cannot call it directly. Recursively find internal picture layers with accessor (ptype == 3), then set the filter:

local anim = vg_load_anim("loading", lottie_json, 200, 200)
anim:accessor(function(ptype, pid, getobj)
if ptype == 3 then -- 3 = picture layer
getobj():set_filter(1) -- 1 = nearest; skip bilinear 4-tap sampling
end
return true -- Continue iteration
end)
anim:set_frame(0)
c:add(anim)
  • Accessor signature (ptype, pid, getobj), with ptype: 1=shape / 2=scene / 3=picture / 4=text. Set only for 3 (vector shapes are unaffected by filters).
  • Traverse once after loading; Lottie structure is static and filter state stays with each paint, so no per-frame resetting is needed.

9. Animation Methods​

Animation paints created by vg_load_anim provide frame control and other general animation methods.

local anim = vg_load_anim("loading", lottie_json, 200, 200)

-- Inspect information
local cur, total, fps = anim:anim_info()

-- Frame control
anim:set_frame(0)
c:add(anim)
c:draw(0, 0)

-- Animation loop: advance each frame
anim:set_frame(1)
c:draw(0, 0)

p:set_frame(frame) → self​

Sets the current frame. Out-of-range frames are clamped to the valid range (not modulo).

  • frame (number) — Frame number
anim:set_frame(0)   -- Frame 0
anim:set_frame(30) -- Frame 30

p:get_frame() → frame​

Gets current frame number.

Return values:

  • frame (number) — Current frame number
local f = anim:get_frame()

p:anim_info() → current, total, fps, duration​

Gets animation information.

Return values:

  • current (integer) — Current frame
  • total (integer) — Total frames
  • fps (number) — Frame rate
  • duration (number) — Total duration (seconds)
local cur, total, fps, dur = anim:anim_info()
print(string.format("frame:%d/%d fps:%.1f dur:%.2fs", cur, total, fps, dur))

p:set_segment(begin, end) → self​

Sets playback segment bounds. anim_info total_frames then reports the segment's frame count.

  • begin (number) — Starting frame
  • end (number) — Ending frame
anim:set_segment(10, 50)  -- Play only frames 10-50

p:get_segment() → begin, end​

Gets current playback segment bounds.

Return values:

  • begin (number) — Starting frame
  • end (number) — Ending frame
local b, e = anim:get_segment()

10. Lottie Methods​

Lottie-specific extensions, available only on paints created by vg_load_anim.

p:set_marker(marker_name) → self​

Selects a named marker segment. Mark named segments in After Effects, then jump directly to them with this method.

  • marker_name (string) — Marker name
anim:set_marker("intro")  -- Jump to the "intro" marker segment

p:tween(from, to, progress) → self​

Interpolates linearly between two frames for smooth transitions.

  • from (number) — Starting frame
  • to (number) — Target frame
  • progress (number) — Interpolation progress [0, 1]; 0=from frame, 1=to frame
anim:tween(0, 30, 0.5)  -- Midpoint between frames 0 and 30

p:tween_to(to) → self​

Starts dynamic frame tweening, locking the current frame as the start and to as the target. Advance it frame by frame with tween_go(progress).

  • to (number) — Target frame

Note: set_frame() or a one-shot tween(from,to,progress) discards the active dynamic tween.

anim:set_frame(0)
anim:tween_to(30) -- Lock interpolation from the current frame (0) to frame 30
-- Then advance progress each frame:
anim:tween_go(0.1) -- At 10%
anim:tween_go(0.5) -- At 50%

p:tween_go(progress) → self​

Advances dynamic tweening started by tween_to(). Must call tween_to() once first, otherwise has no effect.

  • progress (number) — Progress [0, 1]; 0=start frame, 1=target frame

p:set_quality(value) → self​

Sets rendering effect quality.

  • value (integer) — Quality 0-100; higher improves effects with greater performance cost
anim:set_quality(80)

p:gen_slot(slot_json) → id​

Generates a slot to dynamically replace Lottie resources (colors/images/etc.).

  • slot_json (string) — Slot configuration JSON

Return values:

  • id (integer) — Slot ID for subsequent apply_slot / del_slot
local slot_id = anim:gen_slot('{"color": [255, 0, 0]}')

p:apply_slot(id) → self​

Applies a generated slot.

  • id (integer) — Slot ID returned by gen_slot
anim:apply_slot(slot_id)

p:del_slot(id) → self​

Deletes a slot and releases resources.

  • id (integer) — Slot ID to delete
anim:del_slot(slot_id)

p:mark() → {{name, begin, end}, ...}​

Gets animation markers, representing time segments defined in After Effects. Non-animation paints or animations without markers return no value (nil).

Returns an array table of {name: string, begin: number, end: number}.

local markers = anim:mark()
for i, m in ipairs(markers) do
print(i, m[1], m[2], m[3])
end

11. Font Methods​

font:close()​

Unloads the font and releases resources. GC calls this automatically; call manually to reclaim resources earlier.

font:close()

font:name() → string​

Gets the font name or loading path.

Return values:

  • string — Font name
local name = font:name()
print("font:", name)

12. Complete API Index​

Global Factory Functions​

FunctionReturnsDescription
vg_new(w, h [, option [, SCR, x, y]])canvasCreate a canvas
vg_rect(x, y, w, h [, rx, ry])paintRectangle (rounded corners supported)
vg_circle(cx, cy, r)paintCircular
vg_ellipse(cx, cy, rx, ry)paintEllipse
vg_line(x1, y1, x2, y2)paintStraight line
vg_poly({pts} [, closed])paintPolygon/polyline
vg_path()paintEmpty path
vg_text([str, x, y, font, size [, r,g,b]])paintText
vg_scene()paintScene container
vg_load_picture(path [, w, h])paintLoad image file
vg_load_picture_data(data [, mime, w, h])paintLoad image from memory
vg_load_picture_raw(data, w, h [, cs])paintLoad raw ABGR8888 pixels
vg_load_picture_img(img [, sx, sy, sw, sh])paintLoad img object (16/32bpp, optional subregion crop)
vg_load_anim(key, json, w, h)paintLoad Lottie animation
vg_font_load(path)fontLoad font file
vg_font_load_data(name, data [, mime])fontLoad font from memory

Canvas Methods​

MethodReturnsDescription
c:draw(x, y [, flag])—Render to screen
c:add(paint)canvasAppend paint
c:insert(paint [, before])canvasInsert paint (before reference or at end)
c:remove(paint)—Remove paint
c:viewport(x, y, w, h)canvasSet clipping viewport
c:update()canvasTrigger canvas update
c:sync()canvasWait for rendering completion
c:clear()—Clear all paints
c:close()—Destroy canvas
c:info()w, hGet canvas dimensions

Font Methods​

MethodReturnsDescription
f:close()—Unload font (automatic on GC)
f:name()stringGet font name/path

Common Paint Methods​

Lifecycle​

MethodReturnsDescription
p:duplicate()paintDuplicate paint as an independent object

Transforms​

MethodReturnsDescription
p:translate(x, y)selfTranslate (cumulative)
p:rotate(degrees)selfRotate (cumulative, degrees)
p:scale(factor)selfUniform scale (cumulative)
p:set_transform(e11..e33)selfSet absolute 3x3 affine matrix

Common Properties​

MethodReturnsDescription
p:opacity(v)selfOpacity 0-255
p:visible(bool)selfShow/hide
p:blend(method)selfBlending mode 0/1/2/3/16

Clipping and Masking​

MethodReturnsDescription
p:clip(clipper)selfClip
p:mask(target, method)selfMask 0-10

Reading State​

MethodReturnsDescription
p:get_opacity()integerOpacity
p:get_visible()boolVisibility
p:get_transform()9 × numberTransform matrix
p:get_type()integerType 0-4
p:get_aabb()x, y, w, hAABB bounding box
p:get_obb(){{x,y}×4}OBB bounding box
p:intersects(x, y [, w, h])boolIntersection test
p:get_clip()paint | nilClipping paint
p:get_parent()paint | nilParent paint
p:set_id(id)selfSet paint ID
p:get_id()integerGet paint ID
p:set_accessible(bool)selfEnable/disable Picture accessible mode
p:accessor(func)selfRecursively traverse descendants; callback func(type,id,getobj)

Shape Methods​

Path Construction​

MethodReturnsDescription
p:move_to(x, y)selfMove pen
p:line_to(x, y)selfStraight line
p:cubic_to(cx1, cy1, cx2, cy2, x, y)selfCubic Bezier
p:close_path()selfClose path

Fill and Stroke​

MethodReturnsDescription
p:fill(r, g, b [, a])selfFill color
p:stroke(r, g, b, width)selfStroke color + width
p:stroke_width(width)selfStroke width
p:stroke_dash({len,...})selfDash pattern
p:stroke_cap(cap)selfCap 0/1/2
p:stroke_join(join)selfJoin 0/1/2
p:stroke_miterlimit(limit)selfMiter limit

Shape Properties​

MethodReturnsDescription
p:fill_rule(rule)selfFill rule 0/1
p:paint_order(stroke_first)selfStroke/fill order
p:trimpath(begin, end [, sim])selfTrim path [0..1]
p:reset()selfReset path

Gradients​

MethodReturnsDescription
p:gradient_linear(x1, y1, x2, y2, stops)selfLinear gradient fill
p:gradient_radial(cx, cy, r [, fx,fy,fr], stops)selfRadial gradient fill
p:stroke_gradient(type, ...)selfStroke gradient
p:gradient_spread(spread)selfGradient spread 0/1/2
p:get_gradient_spread()integerGet gradient spread
p:gradient_transform(e11..e33)selfGradient transform matrix
p:get_gradient_transform()9 × numberGet gradient transform

Reading Shape Properties​

MethodReturnsDescription
p:get_fill_color()r, g, b, aFill color
p:get_fill_rule()integerFill rule
p:get_stroke_color()r, g, b, aStroke color
p:get_stroke_width()numberStroke width
p:get_stroke_cap()integerStroke cap
p:get_stroke_join()integerJoin style
p:get_stroke_miterlimit()numberMiter limit
p:get_path()cmds, ptsPath data
p:get_gradient()type, params, stopsGradient data
p:get_stroke_dash(){len,...}, offsetDash pattern
p:get_stroke_gradient()type, params, stopsStroke gradient

Text Methods​

MethodReturnsDescription
p:set_font(font)selfSet font
p:set_size(size)selfSet font size
p:set_text(utf8)selfSet text content
p:set_color(r, g, b)selfSet color
p:set_italic(shear)selfItalic shear [0, 0.5]
p:set_outline(w, r, g, b)selfOutline
p:set_gradient(type, ...)selfGradient fill
p:align(x, y)selfAlignment [0, 1]
p:layout(w, h)selfLayout constraints
p:wrap(mode)selfWrapping 0-4
p:spacing(letter, line)selfLetter/line spacing
p:get_text()stringGet text
p:line_count()numberLine count
p:metrics()ascent, descent, linegap, advanceFont metrics
p:glyph_metrics(ch)adv, bearing, x0, y0, x1, y1Glyph metrics

Scene Methods​

MethodReturnsDescription
p:scene_add(child)selfAdd child
p:scene_remove([child])selfRemove child (omitted=clear)
p:scene_insert(target [, before])selfInsert child

Effect Methods​

MethodReturnsDescription
p:effect_blur(sigma [, dir, border, quality])selfGaussian blur
p:effect_shadow(r, g, b, a, angle, dist, sigma [, quality])selfDrop shadow
p:effect_fill(r, g, b, a)selfFill color effect
p:effect_tint(br, bg, bb, wr, wg, wb, intensity)selfTint
p:effect_tritone(sr,sg,sb, mr,mg,mb, hr,hg,hb [, blend])selfTritone
p:clear_effects()selfClear all effects

Picture Methods​

MethodReturnsDescription
p:set_size(w, h)selfSet picture dimensions
p:get_size()w, hGet picture dimensions
p:set_origin(x, y)selfSet normalized origin [0..1]
p:get_origin()x, yGet normalized origin
p:set_filter(method)selfFilter: 0=bilinear, 1=nearest

Animation Methods​

MethodReturnsDescription
p:set_frame(frame)selfSet frame
p:get_frame()numberCurrent frame
p:anim_info()cur, total, fps, durAnimation information
p:set_segment(begin, end)selfSet playback segment
p:get_segment()begin, endCurrent playback segment

Lottie Methods​

MethodReturnsDescription
p:set_marker(name)selfSet marker segment
p:tween(from, to, progress)selfFrame interpolation [0, 1]
p:tween_to(from, to)selfTween to target frame (see §10)
p:tween_go(progress)selfAdvance tween progress [0, 1] (see §10)
p:set_quality(value)selfEffect quality 0-100
p:gen_slot(slot_json)idGenerate slot
p:apply_slot(id)selfApply slot
p:del_slot(id)selfDelete slot
p:mark(){{name, begin, end}}Marker list

13. Complete Example: Animated Logo on a Round Dial​

240×240 round-screen demonstration. All elements are symmetric around the center, fitting a circular dial.

-- ============================================================
-- Animated round-dial logo (240×240)
-- Demonstrates shapes, paths, gradients, strokes, transforms, scenes, duplicate, mask, and text
-- ============================================================

local W, H = 240, 240
local CX, CY = W / 2, H / 2
local R = W / 2 -- Round screen radius
local c = vg_new(W, H)

-- Helper: build a rotation and scaling transform around (cx, cy)
-- M = T(cx,cy) * R(angle) * S(s) * T(-cx,-cy)
local function xform(cx, cy, s, angle)
local rad = math.rad(angle)
local cos_a = math.cos(rad)
local sin_a = math.sin(rad)
return
s * cos_a, -s * sin_a, cx - s * (cx * cos_a - cy * sin_a),
s * sin_a, s * cos_a, cy - s * (cx * sin_a + cy * cos_a)
end

-- ── Background: dark circle (radial gradient) ─────
local bg = vg_circle(CX, CY, R)
bg:gradient_radial(CX, CY, R,
{0, 25, 15, 50, 255,
0.7, 15, 8, 35, 255,
1.0, 8, 4, 20, 255})
c:add(bg)

-- ── Outer decorative ring ────────────────────────
local ring_outer = vg_circle(CX, CY, R - 6)
ring_outer:fill(0, 0, 0, 0)
ring_outer:stroke(100, 80, 180, 1.0)
ring_outer:stroke_dash({6, 4, 2, 4})
ring_outer:stroke_cap(1)
c:add(ring_outer)

-- Solid inner ring
local ring_inner = vg_circle(CX, CY, R - 14)
ring_inner:fill(0, 0, 0, 0)
ring_inner:stroke(60, 50, 120, 0.8)
c:add(ring_inner)

-- ── Tick dots (12, like a clock) ─────────────────
local tick_dot = vg_circle(CX, CY - (R - 10), 2.5)
tick_dot:fill(160, 140, 220)

for i = 0, 11 do
local d = tick_dot:duplicate()
d:set_transform(xform(CX, CY, 1.0, i * 30))
c:add(d)
end

-- 4 larger major ticks
local main_tick = vg_circle(CX, CY - (R - 10), 4)
main_tick:fill(220, 200, 255)

for i = 0, 3 do
local d = main_tick:duplicate()
d:set_transform(xform(CX, CY, 1.0, i * 90))
c:add(d)
end

-- ── Main logo: rounded diamond path ──────────────
local tri = vg_path()
:move_to(CX, 42)
:cubic_to(CX + 15, 42, CX + 52, 70, CX + 58, 88)
:cubic_to(CX + 62, 100, CX + 60, 110, CX + 52, 120)
:line_to(CX + 18, 170)
:cubic_to(CX + 10, 180, CX - 10, 180, CX - 18, 170)
:line_to(CX - 52, 120)
:cubic_to(CX - 60, 110, CX - 62, 100, CX - 58, 88)
:cubic_to(CX - 52, 70, CX - 15, 42, CX, 42)
:close_path()

tri:gradient_linear(CX, 42, CX, 180,
{0, 255, 120, 50, 255,
0.5, 255, 200, 80, 255,
1.0, 240, 80, 30, 255})
tri:stroke(255, 255, 255, 2)
tri:stroke_join(1)
c:add(tri)

-- ── Small inner diamond (duplicate and scale) ────
local tri_inner = tri:duplicate()
tri_inner:set_transform(xform(CX, 110, 0.45, 0))
tri_inner:gradient_linear(CX, 75, CX, 145,
{0, 255, 235, 170, 255,
1.0, 255, 180, 70, 255})
tri_inner:stroke(255, 255, 255, 1.2)
c:add(tri_inner)

-- ── Central glow ────────────────────────────────
local glow = vg_circle(CX, 110, 24)
glow:gradient_radial(CX, 110, 24,
{0, 255, 255, 210, 0,
0.4, 255, 230, 140, 60,
1.0, 255, 180, 60, 180})
glow:opacity(100)
c:add(glow)

local dot = vg_circle(CX, 110, 10)
dot:gradient_radial(CX, 110, 10,
{0, 255, 255, 245, 255,
0.5, 255, 215, 130, 255,
1.0, 255, 160, 50, 230})
c:add(dot)

-- ── Bottom text ────────────────────────────────
local font = vg_font_load("vampire")

local title = vg_text("NATURE", 0, 192, font, 20)
title:set_color(255, 255, 255)
title:opacity(220)
title:align(0.5, 0)
title:translate(CX, 0)
c:add(title)

local subtitle = vg_text("STUDIO", 0, 212, font, 10)
subtitle:set_color(190, 170, 240)
subtitle:set_italic(0.15)
subtitle:opacity(150)
subtitle:align(0.5, 0)
subtitle:translate(CX, 0)
c:insert(subtitle, ring_outer)

-- ── Decorative line scenes with shadows ─────────
local deco = vg_scene()

local l1 = vg_line(36, 110, 66, 110)
l1:stroke(255, 255, 255, 1.5):stroke_cap(1)
deco:scene_add(l1)

local l2 = vg_line(174, 110, 204, 110)
l2:stroke(255, 255, 255, 1.5):stroke_cap(1)
deco:scene_add(l2)

deco:effect_shadow(100, 80, 200, 50, 90, 2, 1.5)
c:add(deco)

-- ── Initial render ──────────────────────────────
c:draw(0, 0)

-- ── Animation loop ──────────────────────────────
local tick = 0
function update_logo()
tick = tick + 1
local t = tick * 0.02

-- Slowly rotate the outer dashed ring
ring_outer:set_transform(xform(CX, CY, 1.0, tick * 0.3))

-- Pulse the inner diamond's scale
local inner_s = 0.45 + 0.025 * math.sin(t * 2.5)
tri_inner:set_transform(xform(CX, 110, inner_s, 0))

-- Make the central circle breathe
dot:opacity(200 + 55 * math.sin(t * 4))

-- Expand the glow
local glow_s = 1.0 + 0.12 * math.sin(t * 3)
glow:set_transform(xform(CX, 110, glow_s, 0))
glow:opacity(70 + 35 * math.sin(t * 3))

-- Make the decorative lines breathe
deco:opacity(170 + 70 * math.sin(t * 2))

c:draw(0, 0)
end

-- Call update_logo() each frame

Example Feature Coverage​

FeatureAPI
Canvas creationvg_new
Circular backgroundvg_circle + gradient_radial
Circle (stroke only)vg_circle + fill(0,0,0,0) + stroke / stroke_dash
Path constructionvg_path + move_to / line_to / cubic_to / close_path
Linear gradientgradient_linear
Radial gradientgradient_radial
Fill and strokefill / stroke / stroke_dash / stroke_cap / stroke_join
Absolute transform (center rotation)set_transform + xform()
Opacityopacity
Duplication + batchingduplicate + loop
Layer insertioncanvas:insert
Scene + shadowvg_scene / scene_add / effect_shadow
Text + font objectsvg_font_load / vg_text / set_italic / align
Renderingcanvas:draw
Animationset_transform + opacity + draw in the frame loop