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
- Global factory functions
- Canvas methods
- Common Paint methods
- Shape methods
- Text methods
- Scene methods
- Scene effects
- Picture methods
- Animation methods
- Lottie methods
- Font methods
- Complete API index
- 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,ylocate 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 coordinatesw,h(number) — Width and heightrx,ry(number, optional, default 0) — Corner radii;rx > 0creates 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 coordinatesr(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 coordinatesrx,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 coordinatesx2,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/falsegives a polyline,truea 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 pathw,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 datamime(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 dataw(integer) — Widthh(integer) — Heightcs(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 byimg_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 returnnil- 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_rgbabyte 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 animationjson(string) — Lottie JSON animation dataw,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 identifierdata(string) — Binary font datamime(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;nilrenders without presenting on screen (offscreen rendering)y(integer) — Screen Y coordinateflag(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 insertbefore(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 Xy(integer) — Viewport top-left Yw(integer) — Viewport widthh(integer) — Viewport height
Note: Call after
canvas:sync(). After changing the viewport, do not calladd/remove/update/drawuntil 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) — Widthh(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 offsety(number) — Y offset
Note:
translateis cumulative, composing with the current matrix. Useset_transformfor 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:
rotateis cumulative. To rotate around another point, useset_transformwith 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:
scaleis 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_transformsets 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 paintmethod(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 coordinatesw,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-leftw,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, ornilif 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, ornilif 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) —trueenables,falsedisables
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=textpid(integer) — Paint ID (fromset_idor 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 traversalfalse— Stop traversal
Performance:
ptypeandpidare lightweight numbers creating no objects. Callgetobj()only when manipulation is needed. To retain a paint reference, store the result ofgetobj()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 pointcx2,cy2(number) — Second control pointx,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-255a(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-255width(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,falsewhen 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 startx2,y2(number) — Gradient endstops(table) — Color stops{offset1, r1, g1, b1, a1, offset2, r2, g2, b2, a2, ...}offsetranges [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 centerr(number) — Outer circle radiusfx,fy,fr(number, optional) — Focal position and radius; default focus is the outer circle centerstops(table) — Color stops (as ingradient_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_linearorgradient_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 andget_gradient_spreadreturn 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 arraypts_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 typeparams...— 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 arrayoffset(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 byvg_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 outliner,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)
- type=1 (linear):
stopsuses the same format asgradient_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=righty(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 unlimitedh(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 tightensline(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 baselinedescent(number) — Depth below baselinelinegap(number) — Line gapadvance(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 insertbefore(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 blurrierdir(integer, optional, default 0) — Direction: 0=both, 1=horizontal, 2=verticalborder(integer, optional, default 0) — Edge handling: 0=duplicate edge pixels, 1=wrapquality(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-255angle(number) — Shadow offset angle (degrees)dist(number) — Shadow offset distancesigma(number) — Blur radiusquality(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 colormr,mg,mb(integer) — Midtone colorhr,hg,hb(integer) — Highlight colorblend(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) — Widthh(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), withptype: 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 frametotal(integer) — Total framesfps(number) — Frame rateduration(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 frameend(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 frameend(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 frameto(number) — Target frameprogress(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-shottween(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 subsequentapply_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 bygen_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
| Function | Returns | Description |
|---|---|---|
vg_new(w, h [, option [, SCR, x, y]]) | canvas | Create a canvas |
vg_rect(x, y, w, h [, rx, ry]) | paint | Rectangle (rounded corners supported) |
vg_circle(cx, cy, r) | paint | Circular |
vg_ellipse(cx, cy, rx, ry) | paint | Ellipse |
vg_line(x1, y1, x2, y2) | paint | Straight line |
vg_poly({pts} [, closed]) | paint | Polygon/polyline |
vg_path() | paint | Empty path |
vg_text([str, x, y, font, size [, r,g,b]]) | paint | Text |
vg_scene() | paint | Scene container |
vg_load_picture(path [, w, h]) | paint | Load image file |
vg_load_picture_data(data [, mime, w, h]) | paint | Load image from memory |
vg_load_picture_raw(data, w, h [, cs]) | paint | Load raw ABGR8888 pixels |
vg_load_picture_img(img [, sx, sy, sw, sh]) | paint | Load img object (16/32bpp, optional subregion crop) |
vg_load_anim(key, json, w, h) | paint | Load Lottie animation |
vg_font_load(path) | font | Load font file |
vg_font_load_data(name, data [, mime]) | font | Load font from memory |
Canvas Methods
| Method | Returns | Description |
|---|---|---|
c:draw(x, y [, flag]) | — | Render to screen |
c:add(paint) | canvas | Append paint |
c:insert(paint [, before]) | canvas | Insert paint (before reference or at end) |
c:remove(paint) | — | Remove paint |
c:viewport(x, y, w, h) | canvas | Set clipping viewport |
c:update() | canvas | Trigger canvas update |
c:sync() | canvas | Wait for rendering completion |
c:clear() | — | Clear all paints |
c:close() | — | Destroy canvas |
c:info() | w, h | Get canvas dimensions |
Font Methods
| Method | Returns | Description |
|---|---|---|
f:close() | — | Unload font (automatic on GC) |
f:name() | string | Get font name/path |
Common Paint Methods
Lifecycle
| Method | Returns | Description |
|---|---|---|
p:duplicate() | paint | Duplicate paint as an independent object |
Transforms
| Method | Returns | Description |
|---|---|---|
p:translate(x, y) | self | Translate (cumulative) |
p:rotate(degrees) | self | Rotate (cumulative, degrees) |
p:scale(factor) | self | Uniform scale (cumulative) |
p:set_transform(e11..e33) | self | Set absolute 3x3 affine matrix |
Common Properties
| Method | Returns | Description |
|---|---|---|
p:opacity(v) | self | Opacity 0-255 |
p:visible(bool) | self | Show/hide |
p:blend(method) | self | Blending mode 0/1/2/3/16 |
Clipping and Masking
| Method | Returns | Description |
|---|---|---|
p:clip(clipper) | self | Clip |
p:mask(target, method) | self | Mask 0-10 |
Reading State
| Method | Returns | Description |
|---|---|---|
p:get_opacity() | integer | Opacity |
p:get_visible() | bool | Visibility |
p:get_transform() | 9 × number | Transform matrix |
p:get_type() | integer | Type 0-4 |
p:get_aabb() | x, y, w, h | AABB bounding box |
p:get_obb() | {{x,y}×4} | OBB bounding box |
p:intersects(x, y [, w, h]) | bool | Intersection test |
p:get_clip() | paint | nil | Clipping paint |
p:get_parent() | paint | nil | Parent paint |
p:set_id(id) | self | Set paint ID |
p:get_id() | integer | Get paint ID |
p:set_accessible(bool) | self | Enable/disable Picture accessible mode |
p:accessor(func) | self | Recursively traverse descendants; callback func(type,id,getobj) |
Shape Methods
Path Construction
| Method | Returns | Description |
|---|---|---|
p:move_to(x, y) | self | Move pen |
p:line_to(x, y) | self | Straight line |
p:cubic_to(cx1, cy1, cx2, cy2, x, y) | self | Cubic Bezier |
p:close_path() | self | Close path |
Fill and Stroke
| Method | Returns | Description |
|---|---|---|
p:fill(r, g, b [, a]) | self | Fill color |
p:stroke(r, g, b, width) | self | Stroke color + width |
p:stroke_width(width) | self | Stroke width |
p:stroke_dash({len,...}) | self | Dash pattern |
p:stroke_cap(cap) | self | Cap 0/1/2 |
p:stroke_join(join) | self | Join 0/1/2 |
p:stroke_miterlimit(limit) | self | Miter limit |
Shape Properties
| Method | Returns | Description |
|---|---|---|
p:fill_rule(rule) | self | Fill rule 0/1 |
p:paint_order(stroke_first) | self | Stroke/fill order |
p:trimpath(begin, end [, sim]) | self | Trim path [0..1] |
p:reset() | self | Reset path |
Gradients
| Method | Returns | Description |
|---|---|---|
p:gradient_linear(x1, y1, x2, y2, stops) | self | Linear gradient fill |
p:gradient_radial(cx, cy, r [, fx,fy,fr], stops) | self | Radial gradient fill |
p:stroke_gradient(type, ...) | self | Stroke gradient |
p:gradient_spread(spread) | self | Gradient spread 0/1/2 |
p:get_gradient_spread() | integer | Get gradient spread |
p:gradient_transform(e11..e33) | self | Gradient transform matrix |
p:get_gradient_transform() | 9 × number | Get gradient transform |
Reading Shape Properties
| Method | Returns | Description |
|---|---|---|
p:get_fill_color() | r, g, b, a | Fill color |
p:get_fill_rule() | integer | Fill rule |
p:get_stroke_color() | r, g, b, a | Stroke color |
p:get_stroke_width() | number | Stroke width |
p:get_stroke_cap() | integer | Stroke cap |
p:get_stroke_join() | integer | Join style |
p:get_stroke_miterlimit() | number | Miter limit |
p:get_path() | cmds, pts | Path data |
p:get_gradient() | type, params, stops | Gradient data |
p:get_stroke_dash() | {len,...}, offset | Dash pattern |
p:get_stroke_gradient() | type, params, stops | Stroke gradient |
Text Methods
| Method | Returns | Description |
|---|---|---|
p:set_font(font) | self | Set font |
p:set_size(size) | self | Set font size |
p:set_text(utf8) | self | Set text content |
p:set_color(r, g, b) | self | Set color |
p:set_italic(shear) | self | Italic shear [0, 0.5] |
p:set_outline(w, r, g, b) | self | Outline |
p:set_gradient(type, ...) | self | Gradient fill |
p:align(x, y) | self | Alignment [0, 1] |
p:layout(w, h) | self | Layout constraints |
p:wrap(mode) | self | Wrapping 0-4 |
p:spacing(letter, line) | self | Letter/line spacing |
p:get_text() | string | Get text |
p:line_count() | number | Line count |
p:metrics() | ascent, descent, linegap, advance | Font metrics |
p:glyph_metrics(ch) | adv, bearing, x0, y0, x1, y1 | Glyph metrics |
Scene Methods
| Method | Returns | Description |
|---|---|---|
p:scene_add(child) | self | Add child |
p:scene_remove([child]) | self | Remove child (omitted=clear) |
p:scene_insert(target [, before]) | self | Insert child |
Effect Methods
| Method | Returns | Description |
|---|---|---|
p:effect_blur(sigma [, dir, border, quality]) | self | Gaussian blur |
p:effect_shadow(r, g, b, a, angle, dist, sigma [, quality]) | self | Drop shadow |
p:effect_fill(r, g, b, a) | self | Fill color effect |
p:effect_tint(br, bg, bb, wr, wg, wb, intensity) | self | Tint |
p:effect_tritone(sr,sg,sb, mr,mg,mb, hr,hg,hb [, blend]) | self | Tritone |
p:clear_effects() | self | Clear all effects |
Picture Methods
| Method | Returns | Description |
|---|---|---|
p:set_size(w, h) | self | Set picture dimensions |
p:get_size() | w, h | Get picture dimensions |
p:set_origin(x, y) | self | Set normalized origin [0..1] |
p:get_origin() | x, y | Get normalized origin |
p:set_filter(method) | self | Filter: 0=bilinear, 1=nearest |
Animation Methods
| Method | Returns | Description |
|---|---|---|
p:set_frame(frame) | self | Set frame |
p:get_frame() | number | Current frame |
p:anim_info() | cur, total, fps, dur | Animation information |
p:set_segment(begin, end) | self | Set playback segment |
p:get_segment() | begin, end | Current playback segment |
Lottie Methods
| Method | Returns | Description |
|---|---|---|
p:set_marker(name) | self | Set marker segment |
p:tween(from, to, progress) | self | Frame interpolation [0, 1] |
p:tween_to(from, to) | self | Tween to target frame (see §10) |
p:tween_go(progress) | self | Advance tween progress [0, 1] (see §10) |
p:set_quality(value) | self | Effect quality 0-100 |
p:gen_slot(slot_json) | id | Generate slot |
p:apply_slot(id) | self | Apply slot |
p:del_slot(id) | self | Delete 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
| Feature | API |
|---|---|
| Canvas creation | vg_new |
| Circular background | vg_circle + gradient_radial |
| Circle (stroke only) | vg_circle + fill(0,0,0,0) + stroke / stroke_dash |
| Path construction | vg_path + move_to / line_to / cubic_to / close_path |
| Linear gradient | gradient_linear |
| Radial gradient | gradient_radial |
| Fill and stroke | fill / stroke / stroke_dash / stroke_cap / stroke_join |
| Absolute transform (center rotation) | set_transform + xform() |
| Opacity | opacity |
| Duplication + batching | duplicate + loop |
| Layer insertion | canvas:insert |
| Scene + shadow | vg_scene / scene_add / effect_shadow |
| Text + font objects | vg_font_load / vg_text / set_italic / align |
| Rendering | canvas:draw |
| Animation | set_transform + opacity + draw in the frame loop |