svg

package module
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-widgets/svg

CI release pkg.go.dev coverage gallery license

Snapshot: turn any RGBA byte buffer (the output of a go-widgets/toolkit widget composition, or any other pixel producer) into a portable, self-contained SVG document.

Animate / Assemble: stitch a timed list of SVG frames (for example from painter's svgrec recorder) into ONE animated SVG, sharing every subtree that does not change between frames.

Pure Go, BSD-3-Clause, no dependency in the library itself (the tests use painter's svgrec). 100% statement coverage.

Why

Widgets in go-widgets/toolkit are pixel-blitting by design — every Draw call writes bytes into a []byte at (x, y). That is great for rendering, less great for embedding a screenshot in a README: raw PNGs travel poorly across dark-mode readers, don't scale on Retina displays, and lose their crispness at any zoom level.

svg.Snapshot wraps the render in an SVG envelope. The SVG declares a viewBox pinned to the render's pixel dimensions and carries the pixels as a base-64 PNG under image-rendering: pixelated. The result:

  • Bit-exact: every pixel you see in the browser is the same pixel the widget produced. No re-vectorisation, no font substitution, no antialiasing drift.
  • Scales crisply: any zoom keeps hard edges (pixelated hint). Perfect for a docs site that hosts one asset but serves it at multiple sizes.
  • Self-contained: one file, zero external assets. Drops into any Markdown renderer that already accepts SVG images (GitHub, GitLab, mkdocs, Hugo, ...).

Use

The root package works against any RGBA byte producer:

import (
    "os"
    "github.com/go-widgets/svg"
)

surface := make([]byte, 4*w*h)  // fill with anything
// ...your draw code here...

f, _ := os.Create("out.svg")
defer f.Close()
svg.Snapshot(f, surface, w, h, "my image")

For go-widgets/toolkit widgets specifically, the sibling widget subpackage removes the manual make + Draw + Snapshot dance:

import (
    "os"
    "github.com/go-widgets/svg/widget"
    "github.com/go-widgets/toolkit"
)

btn := toolkit.NewButton("Click me", nil)
btn.SetBounds(toolkit.Rect{X: 0, Y: 0, W: 200, H: 40})

f, _ := os.Create("button.svg")
defer f.Close()
widget.Snapshot(f, btn, 200, 40, toolkit.DefaultLight(), "widget: button")

// Or a raw PNG (no SVG envelope):
p, _ := os.Create("button.png")
defer p.Close()
widget.PNG(p, btn, 200, 40, toolkit.DefaultLight())

The label argument on Snapshot becomes the SVG's <title> + aria-label for a11y + previewer tooltips. Pass "" to omit.

Animated SVG

frames := []svg.Frame{
    {At: 0, SVG: first},                      // svgrec output
    {At: 100 * time.Millisecond, SVG: second},
}
out, err := svg.Animate(frames, svg.Options{End: time.Second, Title: "demo"})

Assemble returns a Document (SVG(), Slots(), Stats(), Frame(i), Video(...)); Animate is the one-call form.

  • Structure sharing. Frames are parsed into a hash-consed tree: identical subtrees are stored once in <defs> and referenced with <use> (SVG 2 struct, 5.3.2 and 5.5); adjacent identical frames merge into one interval; clip paths are deduplicated globally. Shared subtrees use a <g id> rather than <symbol>, which is clipped to its viewport (5.4.2).
  • Glyph symbols. Frames from svgrec.TextGlyphs define each distinct glyph outline once as a <symbol overflow="visible"> holding one absolute-command <path>, and draw it with <use href x y>. The assembly merges identical outlines across frames; a still expands each <use> back to the shifted <path>, so it stays in svgrec's vocabulary. Thirty frames of text shrink from 1276009 to 93754 bytes (gzip 329796 to 12237).
  • Timing. Pure CSS: one @keyframes per picture toggling visibility, animation-iteration-count: infinite (CSS Animations 1, section 3). prefers-reduced-motion stops it.
  • Safe on hostile input. Frames go through a strict allowlist parse (g rect path image title clipPath defs symbol use; no doctype, script, foreign namespaces, external href); output is escaped. Bounds: DefaultMaxFrames 4096, DefaultMaxBytes 32 MiB (hard 65536 / 256 MiB), 10 min, 16384 px; refusals are typed errors (ErrTooLarge, ErrTiming, ...). Fuzzed (FuzzAssemble, FuzzTiming).
  • WebM. Document.Video drives two interfaces, Rasterizer and VideoEncoder; no encoder is bundled (no pure-Go VP8/VP9 exists yet).

Measured on 60 frames of 1000x700 from a real recorder (bytes):

Scenario Input Naive Assembled Gain
one live region 1486660 1480754 64772 22.9x
static, no cursor 1459380 1453653 24204 60.1x
every row changes 1486660 1480754 218224 6.8x

About 27 ms and 22 MB allocated per 60-frame assembly (M4 Max, one core, machine under load: times indicative, allocation counts exact).

Responsive root and the HTML player

Options.Responsive writes the root with the viewBox only (no width/height), so the picture scales to its container and keeps its ratio; it excludes Width and Height.

Player(svg, PlayerOptions{}) returns one self-contained HTML page that inlines the SVG and drives its CSS animations through the Web Animations API: play/pause (button or Space), a seek bar, elapsed/total time, left/right arrows for 5 s, loop on by default. The SVG stays script-free (it is what GitHub shows through camo in an <img>, which receives no input); the page's CSP admits its one script and its styles by SHA-256 and loads nothing. The input is refused (ErrPlayer) when it holds a script, an event handler, a foreign object, SMIL, a javascript: or remote href, a DOCTYPE or an entity. #t=<ms> opens the page at that time, #t=<ms>&pause holds it there; a headless-Chrome test checks that a seek shows the picture recorded at that time and that a paused player holds it.

Capturing a scenario: capture and capture/webm

capture.Run(setup, steps, capture.Options{W, H, Title, Zone}, observe) plays a scripted scenario against any scene that can DrawTo(painter.Painter) (setup builds the scene and its state once, inside the pinned zone): each Step{Hold, Do} changes the state, the scene is recorded as one frame with its text as shaped glyph outlines (so it scales without loss), and the frames are assembled into one animated, responsive SVG. The result also gives the still of every slot, the strings drawn (outlines hide them from a text scan) and whatever observe returned after each step. capture.HTML wraps the result in the player page. The bytes do not depend on the machine: time.Local is pinned to Options.Zone (UTC by default) while the scene is drawn.

Around it: ParseSize, ResolveFormat (svg, webm or html, inferred from the --out extension and refused when they contradict), DefaultOutDir(app) under the user config directory, and WriteFile, which refuses a path inside a git work tree. capture/webm.Encode(result, w, h, quality) encodes the same frames as a VP8 WebM (avkit); it lives in a subpackage so a user of SVG and HTML does not compile the encoder.

API

Root package (svg):

func Snapshot(w io.Writer, surface []byte, width, height int, label string) (int, error)
  • Returns the byte count written + the first error, mirroring io.Writer.
  • Errors on dimension ≤ 0 or len(surface) != 4*width*height.
  • Errors bubble up from w.Write calls (header, title, body).
  • All XML output escapes the five predefined XML entities in label (both inside <title> and in the aria-label attribute), so a label containing <b>&"'</b> remains valid XML.

Widget subpackage (svg/widget):

func Snapshot(w io.Writer, wg toolkit.Widget, width, height int, theme *toolkit.Theme, label string) (int, error)
func PNG(w io.Writer, wg toolkit.Widget, width, height int, theme *toolkit.Theme) (int, error)
  • Renders wg into a fresh width×height RGBA surface via wg.Draw(painter.NewPixelPainter(surface, width, height), theme), then serialises. Snapshot wraps in an SVG envelope; PNG emits raw PNG bytes.
  • Errors on non-positive dimensions, nil widget, nil theme.
  • Split into a subpackage so the root svg stays dep-free — a consumer that only uses svg.Snapshot([]byte) for a home-grown pixel producer does not pull go-widgets/toolkit into its module graph.

License

BSD-3-Clause.

Documentation

Overview

Package svg turns a rendered RGBA byte buffer (the output of any go-widgets/toolkit widget composition) into a portable SVG document that embeds the pixels as a base64-encoded PNG. The wrapper scales crisply at any zoom level and travels well in READMEs, GitHub issues, docs sites, tweet threads and PDF exports.

Why not a "true" vector renderer? Widgets in go-widgets/toolkit are pixel-blitting by design — every draw call writes bytes into a []byte at (x, y). Converting that pipeline to <rect>/<text>/etc. would either double every widget's implementation or lose the exact alignment users see in-browser. Embedding the render as PNG is bit-exact (any pixel you see in the browser is the same pixel in the SVG) while still giving you the "scales to any DPI" benefit + the "one file, no external assets" portability.

Typical use in a doc-generation script:

surface := make([]byte, 4*w*h)
btn := toolkit.NewButton("Click me", nil)
btn.SetBounds(toolkit.Rect{X: 0, Y: 0, W: w, H: h})
btn.Draw(painter.NewPixelPainter(surface, w, h), toolkit.DefaultLight())
f, _ := os.Create("button.svg")
svg.Snapshot(f, surface, w, h, "widget: button")

Index

Constants

View Source
const (
	DefaultMaxFrames = 4096
	DefaultMaxBytes  = 32 << 20
	// HardMaxFrames and HardMaxBytes cap what [Options] may raise the limits to.
	HardMaxFrames = 65536
	HardMaxBytes  = 256 << 20
	// MaxDuration bounds the whole animation.
	MaxDuration = 10 * time.Minute
	// MinStep is the smallest gap between two frame timestamps.
	MinStep = time.Millisecond
)

Limits and defaults for Assemble.

View Source
const (

	// MaxDim bounds the canvas of a frame and any requested output size.
	MaxDim = 16384
)
View Source
const MaxPlayerBytes = DefaultMaxBytes

MaxPlayerBytes bounds the SVG Player inlines.

View Source
const MaxVideoPixels = 64 << 20

MaxVideoPixels bounds one rasterised frame (width x height).

Variables

View Source
var (
	// ErrNoFrames is returned for an empty frame list.
	ErrNoFrames = errors.New("svg: no frames")
	// ErrTooManyFrames is returned when the frame count exceeds the limit.
	ErrTooManyFrames = errors.New("svg: too many frames")
	// ErrTooLarge is returned when the frames' total size exceeds the limit.
	ErrTooLarge = errors.New("svg: input too large")
	// ErrTiming is returned for timestamps that are not strictly increasing by
	// at least [MinStep], negative, or beyond [MaxDuration].
	ErrTiming = errors.New("svg: invalid timing")
	// ErrSize is returned for a frame whose canvas differs from the first one.
	ErrSize = errors.New("svg: frames differ in canvas size")
	// ErrOptions is returned for invalid [Options].
	ErrOptions = errors.New("svg: invalid options")
)
View Source
var ErrFrame = errors.New("svg: invalid frame")

ErrFrame wraps every refusal of a malformed or out-of-vocabulary frame.

View Source
var ErrPlayer = errors.New("svg: document refused by the player")

ErrPlayer is returned by Player for a document it refuses to inline: not well-formed, not an svg root, or carrying anything that could run (a script, an event handler, a javascript: link, an embedded foreign document).

View Source
var ErrSlot = fmt.Errorf("svg: no such slot")

ErrSlot is returned by Document.Frame for an index outside the timeline.

View Source
var ErrVideo = errors.New("svg: invalid video request")

ErrVideo is returned for an invalid video request.

Functions

func Animate added in v0.8.0

func Animate(frames []Frame, o Options) ([]byte, error)

Animate assembles frames into one animated SVG; see Assemble.

func Player added in v0.10.0

func Player(doc []byte, o PlayerOptions) ([]byte, error)

Player returns ONE self-contained HTML page that plays the animated SVG with a play/pause button, a seek bar, the elapsed and total time, a loop switch, Space to toggle and the arrow keys to step by 5 s. The SVG itself stays script-free: the page drives its CSS animations through the Web Animations API.

The page loads nothing: its Content-Security-Policy admits the one script and the styles by SHA-256 and nothing else (no network, no frames, no forms). A fragment #t=<ms> opens the page at that time, and #t=<ms>&pause holds it there.

The SVG is refused with ErrPlayer when it is not well-formed XML, is not rooted at <svg>, has a DOCTYPE or an entity, an element that can run code or load a document, an on* attribute, or a href that is not a fragment or a data: image. Responsive documents (Options.Responsive) fill the page; others keep their own size.

func Snapshot

func Snapshot(w io.Writer, surface []byte, width, height int, label string) (int, error)

Snapshot writes an SVG document that wraps the RGBA pixels of a widget render. width + height are the buffer's dimensions; label is a short human-readable string embedded as the SVG's <title>/<desc> for a11y + previewer tooltips (pass "" to omit).

The output is a single, self-contained SVG (no external assets) with a <image> child pointing at data:image/png;base64,… so it pastes cleanly into any Markdown renderer that already accepts SVG images (GitHub, GitLab, mkdocs, Hugo, ...).

Returns the number of bytes written + the first error, mirroring the io.Writer convention.

Types

type Document added in v0.8.0

type Document struct {
	// contains filtered or unexported fields
}

Document is an assembled animation.

func Assemble added in v0.8.0

func Assemble(frames []Frame, o Options) (*Document, error)

Assemble turns timestamped svgrec frames into ONE animated SVG.

Every distinct element subtree is emitted once, in <defs> as a <g id>, and referenced with <use href> (SVG 2, 5.3.2 and 5.5); a group is used instead of <symbol> because a symbol is clipped to its viewport (5.4.2). The one exception is the glyph symbol of svgrec's TextGlyphs: it is declared with overflow="visible", so nothing is clipped, and it is merged by path data across frames into one <symbol id="yN"> in <defs>. Long sibling lists are cut at content-defined boundaries, so a frame that changes one region costs about that region. Each distinct picture sits in a <g class="f">, hidden by default, and a CSS @keyframes per picture flips its visibility. The timing function steps(1,end) holds the previous value across each keyframe interval, so the switch happens exactly at the keyframe offset (CSS Animations 1, 3 and 3.1). The output is byte for byte deterministic and contains no script: frames are parsed strictly and anything outside the svgrec vocabulary is refused with ErrFrame.

func (*Document) Duration added in v0.8.0

func (doc *Document) Duration() time.Duration

Duration is the loop length.

func (*Document) Frame added in v0.8.0

func (doc *Document) Frame(i int) ([]byte, error)

Frame returns the still SVG of slot i, with no animation and no sharing, at the recorded size. It is what Document.Video rasterises.

func (*Document) SVG added in v0.8.0

func (doc *Document) SVG() []byte

SVG returns the animated, script-free SVG. The slice is shared: do not modify it.

func (*Document) Slots added in v0.8.0

func (doc *Document) Slots() []Slot

Slots returns the timeline.

func (*Document) Stats added in v0.8.0

func (doc *Document) Stats() Stats

Stats returns the assembly statistics.

func (*Document) Video added in v0.8.0

func (doc *Document) Video(w io.Writer, width, height int, r Rasterizer, enc VideoEncoder) (err error)

Video rasterises every slot of the timeline at width x height (any size: the source is vector) and feeds the frames to enc, writing to w.

type Frame added in v0.8.0

type Frame struct {
	At  time.Duration
	SVG []byte
}

Frame is one recorded frame: the document returned by go-widgets/painter's svgrec.Recorder.SVG, and the time it appeared, measured from any origin (only differences matter).

type Options added in v0.8.0

type Options struct {
	// End is when the last frame disappears (the loop length). Zero means the
	// last frame lasts as long as the one before it (100 ms for a single frame).
	End time.Duration
	// Width and Height set the displayed size; the viewBox is unchanged, so the
	// result stays lossless at any size. Zero keeps the recorded size; setting
	// only one derives the other from the aspect ratio.
	Width, Height int
	// Responsive omits width and height from the root element, which then carries
	// the viewBox only: the document scales to its container and keeps its aspect
	// ratio (preserveAspectRatio defaults to xMidYMid meet). It excludes Width and
	// Height.
	Responsive bool
	// Title is the accessible name of the whole animation (optional).
	Title string
	// MaxFrames and MaxBytes bound the input (frame count and total bytes of
	// all frames). Zero means [DefaultMaxFrames] and [DefaultMaxBytes]; they
	// cannot exceed [HardMaxFrames] and [HardMaxBytes].
	MaxFrames, MaxBytes int
	// contains filtered or unexported fields
}

Options tunes Assemble. The zero value is valid.

type PlayerOptions added in v0.10.0

type PlayerOptions struct {
	// Title is the page title and the accessible name of the player; it falls
	// back to the document's own <title>, then to "Animation".
	Title string
	// Lang is the BCP 47 tag of the page chrome ("en" by default); only "en" and
	// "fr" have labels, any other value falls back to English.
	Lang string
}

PlayerOptions tunes Player. The zero value is valid.

type Rasterizer added in v0.8.0

type Rasterizer interface {
	Rasterize(svg []byte, width, height int) (*image.NRGBA, error)
}

Rasterizer renders a still SVG at a pixel size. Implementations may use any pure-Go rasteriser (for instance go-gfx/gfx/svg); nothing here depends on one.

type Slot added in v0.8.0

type Slot struct {
	Start, Duration time.Duration
	Picture         int // index into the distinct pictures
}

Slot is one stretch of the timeline during which one distinct picture is shown. Adjacent identical frames are merged into one slot.

type Stats added in v0.8.0

type Stats struct {
	Frames        int // input frames
	Slots         int
	Pictures      int // distinct pictures
	Nodes         int // distinct element subtrees
	Shared        int // subtrees emitted once in <defs> and referenced
	Clips         int // distinct clipPaths
	Symbols       int // distinct glyph symbols
	InputBytes    int
	OutputBytes   int
	Width, Height int // recorded canvas
}

Stats describes an assembly.

type VideoEncoder added in v0.8.0

type VideoEncoder interface {
	Open(w io.Writer, width, height int) error
	WriteFrame(img *image.NRGBA, d time.Duration) error
	Close() error
}

VideoEncoder writes a sequence of timed frames as a video container. A WebM (VP8/VP9) encoder is expected to implement it; this package ships none, because no pure-Go one exists and a cgo or exec one is out of policy. Calls come in the order Open, WriteFrame (one per slot, in time order), Close; Close is called even after an error so the encoder can release resources.

Directories

Path Synopsis
Package capture plays a scripted scenario against a painter-drawn scene and records every step as a frame of one animated, resolution-independent SVG (and, through the player page or the capture/webm subpackage, as an HTML page or a video of the same frames).
Package capture plays a scripted scenario against a painter-drawn scene and records every step as a frame of one animated, resolution-independent SVG (and, through the player page or the capture/webm subpackage, as an HTML page or a video of the same frames).
webm
Package webm encodes a capture.Result as a VP8 WebM video of the same frames.
Package webm encodes a capture.Result as a VP8 WebM video of the same frames.
cmd
gallery-render command
Command gallery-render writes an SVG + PNG snapshot of every go-widgets/toolkit widget kind to a directory.
Command gallery-render writes an SVG + PNG snapshot of every go-widgets/toolkit widget kind to a directory.
Package widget wraps the go-widgets/toolkit `Widget` interface with two write-to-io.Writer conveniences:
Package widget wraps the go-widgets/toolkit `Widget` interface with two write-to-io.Writer conveniences:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL