oksvg

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: BSD-3-Clause Imports: 34 Imported by: ? modules, 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

oksvg

This is a fork of srwiley/oksvg, developed at github.com/NimbleMarkets/oksvg as part of the NimbleMarkets ecosystem. It tracks upstream's SVG parsing and rasterization but adds text/font rendering, color-emoji glyphs, SVG patterns, and a number of correctness and concurrency fixes described below.

oksvg is a rasterizer for a partial implementation of the SVG 1.1 specification in Go. Although many SVG elements are not read by oksvg, it is good enough to faithfully produce thousands, but certainly not all, SVG icons available both for free and commercially. A list of supported and unsupported elements is in doc/SVG_Element_List.txt.

oksvg uses the rasterx package to rasterize paths, including the newer 'arc' join-mode.

arcs and caps

Fill rules

fill-rule is parsed from presentation attributes, class declarations and inline styles, with inheritance and per-element overrides. The parsed winding rule is passed to the rasterx scanner. Pixel-correct evenodd rendering requires a scanner implementing SetWinding(false); older ScannerGV versions silently ignored that switch. The local rasterx fix adds parity scan conversion; update to its published release when available. Parsing the property alone does not fix holes when an older scanner remains linked.

Install

go get github.com/NimbleMarkets/oksvg

Import it as:

import "github.com/NimbleMarkets/oksvg"

Go modules resolve the rest of the dependency graph (github.com/srwiley/rasterx, golang.org/x/image, golang.org/x/net) automatically; no manual go get of transitive packages is required.

Replacing upstream oksvg

Starting with the planned v0.1.3 release, applications that import github.com/srwiley/oksvg can use this fork without changing their imports:

replace github.com/srwiley/oksvg => github.com/NimbleMarkets/oksvg v0.1.3

The compatibility fix moves the fork's external tests into package oksvg and removes their self-import of github.com/NimbleMarkets/oksvg. This prevents go mod tidy in consumers such as nttypeset from loading the same fork version under both module paths. The module declaration, production imports, public API, test assertions, and golden images are unchanged. Direct imports of github.com/NimbleMarkets/oksvg continue to work.

Version v0.1.3 must be tagged and published before consumers can pin the replacement above; v0.1.2 does not include this fix. To try an unreleased checkout, replace github.com/srwiley/oksvg with its local directory instead.

What this fork adds

Text (<text> / <tspan>)

<text> and <tspan> are parsed and laid out, including:

  • font-family (with comma-separated fallback lists), font-size (px, pt, em, rem, %), and font-weight.
  • Per-chunk text-anchor (start / middle / end): each new x/y-positioned run of text is measured and anchored independently, matching the SVG text-chunk model.
  • dx / dy relative offsets and kerning (via the font's own kern table).
  • SVG whitespace normalization (collapsing runs of whitespace, trimming across fragment boundaries) per the spec's default xml:space="default" behavior.
  • Glyphs missing from the resolved font render as .notdef rather than being skipped or panicking.

x, y, dx, and dy currently accept a single value, not the SVG-legal list-per-character form (see Known limitations).

Fonts and font registration
oksvg.RegisterFont("My Custom Font", fontBytes)          // a single-face .ttf/.otf
oksvg.RegisterFontCollection("My Font Family", ttcBytes)  // a .ttc; bare name binds to face 0,
                                                            // individual faces are addressable
                                                            // as "My Font Family-0", "-1", ...

A small set of Go fonts (regular and bold) are embedded and registered at init() as the sans-serif / serif / monospace / default fallback faces, so text renders out of the box with no setup.

System fonts (and, on macOS, Apple Color Emoji) are not loaded at import time. Reading them eagerly would cost every importer of this package real memory whether or not they ever render text or emoji — Apple Color Emoji's .ttc alone is roughly 180 MB. Instead they are loaded lazily, at most once, the first time a <text> element is laid out. If you want to pay that cost up front (e.g. to avoid a first-render latency spike), call it explicitly:

oksvg.LoadSystemFonts() // safe to call concurrently; a no-op after the first call
Color emoji (sbix bitmap glyphs)

Fonts that carry an Apple-style sbix bitmap glyph table (Apple Color Emoji being the common case) are parsed and cached, and are hardened against malformed/adversarial font data (no panics on truncated tables, bad offsets, or oversized images).

On macOS, regional-indicator pairs (flag emoji like 🇺🇸) are additionally resolved through Apple Color Emoji's internal ligature table, which maps each pair of regional-indicator glyphs to a single pre-composed flag glyph — the same thing the OS text engine does. Because that table's structure is not documented and was reverse-engineered from one specific font build, this fork gates its use on an exact match of the font's version string (name ID 5, "21.4d3e1" — see icon_cursor_darwin.go for the extraction provenance). If the installed Apple Color Emoji is a different version, flags silently degrade to rendering each regional-indicator rune as its own glyph (still correct-ish visually, just not a single composed flag). There is no morx/ligature-table parser; the mapping is a fixed, hand-built table for that one font version.

Bitmap glyph compositing requires SvgIcon.DrawTarget

Color-emoji (and any other bitmap) glyphs are not drawn by the vector rasterizer — they are composited directly onto an image/draw.Image. Set SvgIcon.DrawTarget to the same image you're rasterizing paths into, or bitmap glyphs are silently skipped (vector content still draws normally):

icon, err := oksvg.ReadIcon("emoji-flag.svg", oksvg.WarnErrorMode)
if err != nil {
    log.Fatal(err)
}

w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
img := image.NewRGBA(image.Rect(0, 0, w, h))

icon.SetTarget(0, 0, float64(w), float64(h))
icon.DrawTarget = img // required for bitmap/color-emoji glyphs to composite

scanner := rasterx.NewScannerGV(w, h, img, img.Bounds())
raster := rasterx.NewDasher(w, h, scanner)
icon.Draw(raster, 1.0)

Paths and bitmap glyphs are interleaved in the SVG's document order when drawn, so a path that overlaps or follows a <text> run z-orders correctly against it.

Explicit SVG image resources

ReadIconStreamWithImages(reader, images, errorMode...) accepts a map of already decoded image.Image values keyed by <image href> (also xlink:href and legacy src). It performs no network or filesystem access and no data URL decoding. The regular ReadIconStream does not load image resources. Keep supplied images and the map immutable during parsing; keep images immutable while drawing.

Images support explicit dimensions, positioning, inherited transforms and opacity, display/visibility, and preserveAspectRatio (none, meet, slice). Each decoded image is capped at 4096 pixels per edge and 4 Mi pixels total. Set SvgIcon.DrawTarget to the same image used by the rasterizer so bitmap images and vector paths are composited in document order.

Images inside patterns and markers are unsupported: strict mode reports an error; warning and ignore modes skip those images while retaining vector content. Negative image dimensions are errors; zero dimensions skip drawing.

Patterns (<pattern>)

<pattern> elements declared in <defs> are supported, including:

  • patternUnits / patternContentUnits of userSpaceOnUse or objectBoundingBox.
  • patternTransform.
  • fill="url(#id)" / stroke="url(#id)" references, resolved as forward references — a <pattern> (or gradient) defined later in the document than the element that references it still resolves correctly, because url() references are fixed up after the whole document is parsed.
  • Gradient xlink:href/href stop inheritance (one gradient borrowing another's stops).

Rendered pattern tiles are capped at 4096 px per axis regardless of the SVG's requested scale, to bound memory use against adversarial input.

Markers (<marker>)

marker-start, marker-mid, marker-end, and the marker shorthand draw a <marker>'s content at the vertices of <path>, <line>, <polyline>, and <polygon> elements, so arrowheads drawn as markers (as diagram renderers such as go-mermaid and Graphviz emit) appear. Supported:

  • viewBox, refX/refY, markerWidth/markerHeight, and preserveAspectRatio="none" (otherwise the content scales uniformly).
  • markerUnits of strokeWidth (the default) or userSpaceOnUse.
  • orient of auto, auto-start-reverse, or an angle in degrees, deg, rad, grad, or turn. auto follows the path's direction, including Bézier tangents, and bisects the turn at interior vertices; a closed subpath joins its ends.
  • A <marker> outside <defs> is a definition, never drawn where it appears.

Markers are placed when the referencing element is parsed. Marker placement adds at most 100,000 paths per document; over budget, strict mode reports an error and other modes stop adding markers.

Percentage lengths

Shape geometry (x, y, width, height, cx, cy, r, rx, ry, x1…y2), <use> offsets, and text positions accept percentages of the root viewport: its width for horizontal lengths, its height for vertical ones, and the normalized diagonal for r. A <rect width="100%" height="100%"> background now fills the image instead of being dropped. A percentage width/height on the root <svg> leaves the viewBox in charge.

Thread-safety
  • After this fork's concurrency fixes, calling SvgIcon.Draw concurrently from multiple goroutines on the same, already-parsed SvgIcon is safe, including when patterns or color-emoji glyphs are involved, as long as each call targets its own raster/DrawTarget destination (drawing two goroutines into the same destination image is a data race at the image level, not an oksvg one).
  • Parsing (ReadIcon/ReadIconStream/ReadReplacingCurrentColor) and any API that mutates a parsed SvgIcon (e.g. SetTarget, or reaching into its fields) are not thread-safe. Parse once, then either draw concurrently via Draw, or give each goroutine its own parsed copy if it needs to mutate icon state.
  • RegisterFont, RegisterFontCollection, and LoadSystemFonts are safe to call concurrently with each other and with rendering.

Behavior changes vs srwiley/oksvg

This fork intentionally changed a few behaviors from upstream. If you're migrating from srwiley/oksvg, check whether any of these affect your output:

  • Default stroke-width is now 1.0, matching the SVG specification's initial value. Upstream defaulted to 2.0.
  • Default stroke-linejoin is now miter, matching the SVG specification's initial value (with the default stroke-miterlimit of 4). Upstream defaulted to bevel, which chamfered every stroked corner that did not set stroke-linejoin explicitly (srwiley/oksvg#52).
  • SvgIcon.SetTarget now correctly accounts for a non-zero viewBox origin (viewBox="x y w h" with x/y != 0). Upstream ignored the origin, which shifted content for icons using such a viewBox.
  • A style="..." attribute now wins over presentation attributes (e.g. fill="red" style="fill:blue" renders blue), per the SVG/CSS cascade. Upstream's precedence did not consistently honor this.
  • fill-opacity / stroke-opacity now replace rather than compound across nested elements (an inner element's fill-opacity is not multiplied by its ancestors'). Group opacity still compounds (see Known limitations).
  • Pattern.GetColorFunction's signature changed: it now takes an oksvg.ObjectBounds (an axis-aligned {X, Y, W, H float64} user-space bounding box) instead of its previous parameter shape, so objectBoundingBox-unit patterns can be positioned correctly. Code that called this directly (most consumers only call Draw, which doesn't need to) will need to update the call site.
  • Error-mode handling is now consistent for both element and style errors. StrictErrorMode aborts the parse on either kind of error; WarnErrorMode logs and continues; IgnoreErrorMode continues silently. Upstream's handling of style errors was inconsistent with its handling of unrecognized elements.
  • objectBoundingBox gradients follow the shape's transform. The gradient is laid out in the element's own bounding box and then rotated/skewed/scaled with it, per the specification. Previously it was fitted to the axis-aligned device-space extent, so a horizontal gradient on a rotated rect stayed horizontal. As part of this the object bounding box is now the tight geometry extent (curve extrema, not Bézier control points, and excluding the stroke), which also repositions objectBoundingBox gradients on stroked curves and on arc-built ellipses.
  • A forward-referenced <pattern> that fails to compile is an error in StrictErrorMode, the same as a pattern declared before its use. Previously the error was swallowed when the pattern appeared later in the document than the element using it.
  • Resource limits on untrusted input. <use> expansion is bounded by a document-wide replay budget (100,000 definition elements) in addition to the nesting-depth cap, since sibling references can fan out exponentially at shallow depth; once spent, further <use> replay stops (an error in StrictErrorMode, logged once in WarnErrorMode). sbix bitmap glyphs larger than 1024 px on a side are skipped before decoding, so a registered font cannot force an arbitrarily large PNG allocation; each distinct glyph is decoded once per document and shared, and distinct glyphs are charged against a 32 Mpx per-document budget, beyond which glyphs render as vector outlines. Pattern references are capped at 40 levels during compilation and drawing. Each Draw permits at most 1,024 pattern tiles and 32 Mpx of cumulative tile allocation, with a 4,096 px per-axis tile cap. Patterns exceeding draw limits paint transparent; excessive compilation depth follows the parser's error mode. Definition storage is limited to 100,000 entries, counting copies in ancestor replay lists. On exhaustion, strict mode errors; permissive modes discard incomplete definitions and skip further definition collection while continuing to parse ordinary shapes.

Known limitations

  • <image> requires host-supplied resources via ReadIconStreamWithImages. The parser does not fetch files or URLs or decode data URIs. Images inside patterns and markers are unsupported.
  • Group opacity is approximated per-primitive, not true group compositing. A <g opacity="0.5"> multiplies its descendants' own fill/stroke opacity rather than rendering the group to an offscreen buffer and compositing that as a whole; overlapping shapes within the same semi-transparent group will show seams where upstream SVG renderers would not.
  • userSpaceOnUse gradient/pattern coordinates given as percentages are not resolved against the SVG viewport. Percentages are only meaningful for objectBoundingBox-unit gradients/patterns today.
  • Flag ligatures are pinned to one Apple Color Emoji font version (see Color emoji, above); there is no general morx/ligature-table parser, so a future macOS font update that changes glyph IDs will fall back to per-rune flag rendering until this fork's table is refreshed.
  • Markers are not clipped to their viewport (overflow is treated as visible), a marker referenced before its <marker> element is read is not drawn, and markers on shapes inside marker content are not drawn. Text inside a marker is ignored.
  • Percentage lengths resolve against the root viewport, not the nearest nested <svg>.
  • x, y, dx, dy on <text>/<tspan> accept a single value, not the SVG-legal space/comma-separated list that positions individual characters.
Extra non-standard features

In addition to arc as a valid stroke-linejoin value, oksvg also allows arc-clip, the arc analog of miter-clip, plus some extra capping and gap values. It can also specify different capping functions for line starts and ends.

Example renderings

Example renderings of unedited open-source SVG files by oksvg and rasterx are shown below.

Thanks to Freepik from Flaticon, licensed under Creative Commons 3.0, for the example icons shown below, which are also used as test icons in the testdata folder.

Jupiter

lander

mountains

bus

License

BSD 3-Clause. See LICENSE.

SVG text configuration and measurement: see TEXT.md.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultStyle = PathStyle{
	FillOpacity:       1.0,
	LineOpacity:       1.0,
	LineWidth:         1.0,
	DashOffset:        0.0,
	MiterLimit:        4.0,
	UseNonZeroWinding: true,

	LineCap:  rasterx.ButtCap,
	LineJoin: rasterx.Miter,

	FontFamily: "sans-serif",
	FontSize:   12.0,
	TextAnchor: "start",
	FontWeight: "normal",
	// contains filtered or unexported fields
}

DefaultStyle sets the default PathStyle to fill black, winding rule, full opacity, no stroke, ButtCap line end and Miter line connect, with default font settings.

Functions

func ConfigureTextFonts added in v0.1.5

func ConfigureTextFonts(options TextFontOptions) error

func LoadSystemFonts

func LoadSystemFonts()

LoadSystemFonts loads the platform's system and emoji/symbol fonts into the font registry. It is safe to call concurrently and does the work at most once (subsequent calls are no-ops). oksvg calls it automatically the first time a <text> element is laid out, so the (large) emoji fonts are read from disk only when text is actually rendered rather than at package import. Callers that register fonts before rendering, or that want the load cost paid up front, may call it explicitly.

func ParseSVGColor

func ParseSVGColor(colorStr string) (color.Color, error)

ParseSVGColor parses an SVG color string in all forms including all SVG1.1 names, obtained from the image.colornames package

func ParseSVGColorNum

func ParseSVGColorNum(colorStr string) (r, g, b uint8, err error)

ParseSVGColorNum reads the SVG color string e.g. #FBD9BD

func RegisterFont

func RegisterFont(family string, fontBytes []byte) error

RegisterFont registers a font under the given family name.

func RegisterFontAlias added in v0.1.5

func RegisterFontAlias(alias, family string) error

RegisterFontAlias maps an alias (including a CSS generic family) to an already registered family and its variants. It does not copy or parse font data.

func RegisterFontCollection

func RegisterFontCollection(family string, collectionBytes []byte) error

RegisterFontCollection registers all fonts inside a TTC/collection.

func RegisterFontFamily added in v0.1.5

func RegisterFontFamily(family string, source FaceSource) error

RegisterFontFamily atomically registers all four faces under a CSS family. Source calls and parsing happen before taking the registry lock. It does not load system fonts or import a font bundle. Each face is limited to 32 MiB.

Types

type ErrorMode

type ErrorMode uint8

ErrorMode is the for setting how the parser reacts to unparsed elements

const (
	// IgnoreErrorMode skips un-parsed SVG elements.
	IgnoreErrorMode ErrorMode = iota

	// WarnErrorMode outputs a warning when an un-parsed SVG element is found.
	WarnErrorMode

	// StrictErrorMode causes an error when an un-parsed SVG element is found.
	StrictErrorMode
)

type FaceSource added in v0.1.5

type FaceSource interface {
	Face(family, variant string) ([]byte, error)
}

FaceSource supplies immutable font bytes; it is compatible with ntfonts.Source. Font registration/configuration should finish before measuring/parsing documents.

type IconCursor

type IconCursor struct {
	PathCursor

	StyleStack []PathStyle
	// contains filtered or unexported fields
}

IconCursor is used while parsing SVG files.

func (*IconCursor) PushStyle

func (c *IconCursor) PushStyle(attrs []xml.Attr) error

PushStyle parses the style attributes of an element and pushes the resulting style onto the style stack. Properties are applied in CSS precedence order: class selectors (lowest), then presentation attributes, then the inline style="" attribute (highest). Per-property parse errors are handled according to the error mode: StrictErrorMode aborts the parse; Warn logs and skips the property; Ignore skips silently. The style is always pushed (even when a property is skipped) so the stack stays balanced with EndElement pops.

func (*IconCursor) ReadGradAttr

func (c *IconCursor) ReadGradAttr(attr xml.Attr) (err error)

ReadGradAttr reads an SVG gradient attribute

func (*IconCursor) ReadGradURL

func (c *IconCursor) ReadGradURL(v string, defaultColor interface{}) (grad rasterx.Gradient, ok bool)

ReadGradURL reads an SVG format gradient url Since the context of the gradient can affect the colors the current fill or line color is passed in and used in the case of a nil stopClor value

func (*IconCursor) ReadPatternURL

func (c *IconCursor) ReadPatternURL(v string) (pattern *Pattern, ok bool)

ReadPatternURL parses an SVG pattern url reference. It is a thin wrapper over readPatternURL that preserves the historical (pattern, ok) signature; any compile error is dropped (ok == false).

type ObjectBounds

type ObjectBounds struct {
	X, Y, W, H float64
}

ObjectBounds is the axis-aligned bounding box of the object being painted, expressed in user space (pre-transform). It positions objectBoundingBox gradients and patterns.

type PathCursor

type PathCursor struct {
	rasterx.Path

	ErrorMode ErrorMode
	// contains filtered or unexported fields
}

PathCursor is used to parse SVG format path strings into a rasterx Path

func (*PathCursor) AddArcFromA

func (c *PathCursor) AddArcFromA(points []float64)

AddArcFromA adds a path of an arc element to the cursor path to the PathCursor

func (*PathCursor) CompilePath

func (c *PathCursor) CompilePath(svgPath string) error

CompilePath translates the svgPath description string into a rasterx path. All valid SVG path elements are interpreted to rasterx equivalents. The resulting path element is stored in the PathCursor.

func (*PathCursor) EllipseAt

func (c *PathCursor) EllipseAt(cx, cy, rx, ry float64)

EllipseAt adds a path of an elipse centered at cx, cy of radius rx and ry to the PathCursor

func (*PathCursor) GetPoints

func (c *PathCursor) GetPoints(dataPoints string) error

GetPoints reads a set of floating point values from the SVG format number string, and add them to the cursor's points slice.

It tokenizes dataPoints as a run of SVG numbers: a number may start with a sign (+/-), contains digits and (via ReadFloat) one or more decimal points, and may end with an exponent marker ('e' or 'E') followed by an optional sign and digits. A '+' or '-' that is not part of an exponent starts a new number, matching the SVG grammar for lists of numbers packed together without whitespace (e.g. "1-2" is two numbers, "1e-2" is one).

func (*PathCursor) ReadFloat

func (c *PathCursor) ReadFloat(numStr string) error

ReadFloat reads a floating point value and adds it to the cursor's points slice.

type PathStyle

type PathStyle struct {
	FillOpacity, LineOpacity          float64
	LineWidth, DashOffset, MiterLimit float64
	Dash                              []float64
	UseNonZeroWinding                 bool

	LineGap     rasterx.GapFunc
	LeadLineCap rasterx.CapFunc // This is used if different than LineCap
	LineCap     rasterx.CapFunc
	LineJoin    rasterx.JoinMode

	FontFamily       string
	FontSize         float64
	TextAnchor       string
	FontWeight       string
	FontStyle        string
	DominantBaseline string
	// contains filtered or unexported fields
}

PathStyle holds the state of the SVG style.

type Pattern

type Pattern struct {
	ID                  string
	X, Y, Width, Height float64
	Units               string // "userSpaceOnUse" or "objectBoundingBox"
	ContentUnits        string // "userSpaceOnUse" or "objectBoundingBox"
	Transform           rasterx.Matrix2D
	Paths               []SvgPath
}

Pattern holds the data of an SVG pattern element.

func (*Pattern) GetColorFunction

func (p *Pattern) GetColorFunction(opacity float64, objBounds ObjectBounds, parentTransform rasterx.Matrix2D) rasterx.ColorFunc

GetColorFunction returns a ColorFunc that implements the tiling logic for this pattern. objBounds is the user-space bounding box of the painted object and parentTransform is the accumulated draw transform (user space -> device).

type SvgIcon

type SvgIcon struct {
	ViewBox       struct{ X, Y, W, H float64 }
	Titles        []string // Title elements collect here
	Descriptions  []string // Description elements collect here
	Grads         map[string]*rasterx.Gradient
	Patterns      map[string]*Pattern
	Defs          map[string][]definition
	SVGPaths      []SvgPath
	SVGImages     []SvgImage
	Transform     rasterx.Matrix2D
	DrawTarget    draw.Image
	MissingGlyphs int // Missing characters laid out with the selected face's .notdef glyph.
	// contains filtered or unexported fields
}

SvgIcon holds data from parsed SVGs.

func ReadIcon

func ReadIcon(iconFile string, errMode ...ErrorMode) (*SvgIcon, error)

ReadIcon reads the Icon from the named file. This only supports a sub-set of SVG, but is enough to draw many icons. If errMode is provided, the first value determines if the icon ignores, errors out, or logs a warning if it does not handle an element found in the icon file. Ignore warnings is the default if no ErrorMode value is provided.

func ReadIconStream

func ReadIconStream(stream io.Reader, errMode ...ErrorMode) (*SvgIcon, error)

ReadIconStream reads the Icon from the given io.Reader. This only supports a sub-set of SVG, but is enough to draw many icons. If errMode is provided, the first value determines if the icon ignores, errors out, or logs a warning if it does not handle an element found in the icon file. Ignore warnings is the default if no ErrorMode value is provided.

func ReadIconStreamWithImages added in v0.1.4

func ReadIconStreamWithImages(stream io.Reader, images map[string]image.Image, errMode ...ErrorMode) (*SvgIcon, error)

ReadIconStreamWithImages permits only already-decoded images in the supplied allowlist, keyed by href. It never reads files, fetches URLs, or decodes data URLs. The caller must keep images immutable while the icon is in use.

func ReadReplacingCurrentColor

func ReadReplacingCurrentColor(stream io.Reader, currentColor string, errMode ...ErrorMode) (icon *SvgIcon, err error)

ReadReplacingCurrentColor replaces currentColor value with specified value and loads SvgIcon as ReadIconStream do. currentColor value should be valid hex, rgb or named color value.

func (*SvgIcon) Draw

func (s *SvgIcon) Draw(r *rasterx.Dasher, opacity float64)

Draw rasterizes the icon. Vector shapes (SVGPaths) are painted into r, a rasterx.Dasher. Bitmap glyphs (SVGImages, e.g. color emoji) are composited into s.DrawTarget; if DrawTarget is nil they are skipped. Paths and images are interleaved by their draw-order stamp so document z-order is preserved. On equal or zero order, paths are drawn before images (legacy behavior).

func (*SvgIcon) SetTarget

func (s *SvgIcon) SetTarget(x, y, w, h float64)

SetTarget sets the Transform matrix to draw within the bounds of the rectangle arguments, accounting for a non-zero viewBox origin. Zero viewBox dimensions fall back to a scale of 1 on that axis to avoid Inf/NaN.

type SvgImage

type SvgImage struct {
	Image     image.Image
	Transform rasterx.Matrix2D
	Opacity   float64
	// contains filtered or unexported fields
}

SvgImage represents a parsed bitmap glyph/image and its transform/opacity properties.

func (*SvgImage) DrawTransformed

func (svgi *SvgImage) DrawTransformed(dst draw.Image, opacity float64, t rasterx.Matrix2D)

DrawTransformed draws the SvgImage onto the destination image, applying the full affine transform (translation, scaling, rotation, and skew) and opacity in a single pass via golang.org/x/image/draw. There is no intermediate allocation: output is written directly into dst and is naturally clipped to dst's own bounds, regardless of how large the transform's scale factors are.

type SvgPath

type SvgPath struct {
	PathStyle
	Path rasterx.Path
	// contains filtered or unexported fields
}

SvgPath binds a style to a path.

func (*SvgPath) Draw

func (svgp *SvgPath) Draw(r *rasterx.Dasher, opacity float64)

Draw the compiled SvgPath into the Dasher.

func (*SvgPath) DrawTransformed

func (svgp *SvgPath) DrawTransformed(r *rasterx.Dasher, opacity float64, t rasterx.Matrix2D)

DrawTransformed draws the compiled SvgPath into the Dasher while applying transform t.

func (*SvgPath) GetFillColor

func (svgp *SvgPath) GetFillColor() color.Color

GetFillColor returns the fill color of the SvgPath if one is defined and otherwise returns colornames.Black

func (*SvgPath) GetLineColor

func (svgp *SvgPath) GetLineColor() color.Color

GetLineColor returns the stroke color of the SvgPath if one is defined and otherwise returns colornames.Black

func (*SvgPath) SetFillColor

func (svgp *SvgPath) SetFillColor(clr color.Color)

SetFillColor sets the fill color of the SvgPath

func (*SvgPath) SetLineColor

func (svgp *SvgPath) SetLineColor(clr color.Color)

SetLineColor sets the line color of the SvgPath

type TextFontOptions added in v0.1.5

type TextFontOptions struct {
	FallbackFamilies   []string
	DisableSystemFonts bool
}

TextFontOptions configures the existing process-wide registry. FallbackFamilies are tried after every CSS family and before Go fonts. Their order is preserved. Configure once at host startup, as with RegisterFont. Changing registrations between measurement and parsing can change metrics.

type TextMetrics added in v0.1.5

type TextMetrics struct {
	Advance, Ascent, Descent, XHeight float64
	MissingGlyphs                     int
}

func MeasureText added in v0.1.5

func MeasureText(text string, style TextStyle) TextMetrics

MeasureText measures a single unnormalized text run with the same fallback, kerning and glyph advances as SVG layout. It does not shape complex scripts.

type TextStyle added in v0.1.5

type TextStyle struct {
	Family, Weight, Style string
	Size                  float64
}

TextStyle is the font selection used by MeasureText and SVG text layout.

Jump to

Keyboard shortcuts

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