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
- Variables
- func Animate(frames []Frame, o Options) ([]byte, error)
- func Player(doc []byte, o PlayerOptions) ([]byte, error)
- func Snapshot(w io.Writer, surface []byte, width, height int, label string) (int, error)
- type Document
- func (doc *Document) Duration() time.Duration
- func (doc *Document) Frame(i int) ([]byte, error)
- func (doc *Document) SVG() []byte
- func (doc *Document) Slots() []Slot
- func (doc *Document) Stats() Stats
- func (doc *Document) Video(w io.Writer, width, height int, r Rasterizer, enc VideoEncoder) (err error)
- type Frame
- type Options
- type PlayerOptions
- type Rasterizer
- type Slot
- type Stats
- type VideoEncoder
Constants ¶
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.
const (
// MaxDim bounds the canvas of a frame and any requested output size.
MaxDim = 16384
)
const MaxPlayerBytes = DefaultMaxBytes
MaxPlayerBytes bounds the SVG Player inlines.
const MaxVideoPixels = 64 << 20
MaxVideoPixels bounds one rasterised frame (width x height).
Variables ¶
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") )
var ErrFrame = errors.New("svg: invalid frame")
ErrFrame wraps every refusal of a malformed or out-of-vocabulary frame.
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).
var ErrSlot = fmt.Errorf("svg: no such slot")
ErrSlot is returned by Document.Frame for an index outside the timeline.
var ErrVideo = errors.New("svg: invalid video request")
ErrVideo is returned for an invalid video request.
Functions ¶
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 ¶
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
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) Frame ¶ added in v0.8.0
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
SVG returns the animated, script-free SVG. The slice is shared: do not modify it.
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
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
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
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
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
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: |