Help us shape the future of Go! Take the 2026 Go Developer Survey

oksvg

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: BSD-3-Clause Imports: 20 Imported by: 0

README

Go API Reference

oksvg

Oksvg is a rasterizer for a partial implementation of the SVG2.0 specification in Go.

This is GOUI's fork of fyne-io/oksvg, originally by srwiley. Fixes are proposed upstream separately from fork-specific module changes. The repeated-arc fix is tracked in fyne-io/oksvg#6.

Although many SVG elements will not be 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 valid and invalid elements is in the doc folder.

The package can be installed by running:

go get github.com/golang-gui/oksvg@latest
Rendering an icon
icon, err := oksvg.ReadIconStream(strings.NewReader(svgSource), oksvg.StrictErrorMode)
if err != nil {
    return err
}
bitmap := icon.Rasterize(64, 64)

Rasterize returns a new, caller-owned premultiplied *image.RGBA, with transparent pixels outside the artwork. It applies viewBox and preserveAspectRatio (default: xMidYMid meet). Invalid target sizes return nil. It has no image cache and does not change SetTarget/Transform state; concurrent calls are safe while the parsed icon is not modified by callers. It uses the pure Go scanFT scanner for both nonzero and evenodd filling. No cgo or native SVG library is required.

The existing SetTarget/Draw interface remains available. SetTarget explicitly stretches the viewBox to its target rectangle. A caller supplying a scanner to Draw must choose one that implements the requested winding rule; rasterx's ScannerGV does not implement evenodd filling.

Parsing and supported SVG features

DOCTYPE declarations, XML metadata attributes such as xml:space, and foreign namespace metadata are accepted. The parser never fetches DTDs, expands custom entities, or loads external files or URLs. Foreign attributes cannot override ordinary SVG attributes with the same local name.

The icon subset supports shapes and paths, affine transforms, local use references, simple class rules, inline styles, currentColor, fill rules, fill/stroke opacity, stroke caps/joins/dashes, and linear/radial gradients. Definitions may follow their uses. Inline styles override presentation attributes, and inherited fill/stroke opacity is overridden rather than multiplied by a child's declaration.

Compact arc flags, percentage geometry and stroke lengths, 96-dpi absolute length units, and local paint fallbacks such as url(#paint) currentColor are supported. Function colors include RGB/HSL alpha and space/slash forms. Relative intrinsic em/ex/rem sizes can accompany an explicit viewBox; font-relative shape lengths still require an unavailable font context.

SVG 2 geometry properties x, y, width, height, cx, cy, r, rx and ry also accept supported lengths/percentages in class rules and inline styles, using the same precedence as paint properties. Geometry is local to each element and does not implicitly inherit. This does not add full CSS layout, calc(), or CSS path syntax.

StrictErrorMode rejects recognized unsupported rendering features, including object/group opacity other than 1, clipping, masks, filters, text and animation. Unknown attributes are ignored for forward compatibility. IgnoreErrorMode (the legacy default) and WarnErrorMode remain available; unsupported elements are skipped with their entire subtrees. Malformed XML, numbers, paths and missing/cyclic local references fail in every mode and return no partial icon.

See the feature list and the parser/rasterization design for scope and limitations. Known renderer limitations and online corpus results are recorded in the corpus validation notes. Reversing round joins, collinear curve cusps, and implicit subpaths following closepath have regression coverage; remaining reference differences are recorded separately.

Path and transform coordinates round consistently to the nearest fixed-point unit. Dashed strokes retain fractional segment distances and handle zero-length dash/gap boundaries; repeated curve samples preserve stroke normals. Coverage at negative canvas coordinates is clipped before painting. Validation separates geometry and color errors from small antialiasing differences, and uses analytic expectations or suite references when a browser lacks a feature such as miter-clip.

Radial gradients with a zero-radius focus support the SVG 2 external-focus geometry, leaving regions outside the gradient cone transparent. Near-linear stroke curves are reduced within a bounded raster-space tolerance to keep their caps consistent with the emitted segment. See the radial-gradient scope for remaining boundary cases and the validation notes for reference exceptions.

Oksvg uses the maintained rasterx fork for path stroking, including the extended 'arc' join mode.

The current development branches use the golang-gui module paths throughout. Renderer dependencies are pinned to their v0.1.0 release tags. These tags must be available on their remotes before standalone module resolution; local integration before pushing uses a temporary Go workspace. See the validation notes for the staging and release order. Legacy Draw users must use the matching fork's rasterx types.

arcs and caps

Extra non-standard features

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

Rasterizations of SVG to PNG from creative commons 3.0 sources

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

Thanks to Freepik from Flaticon Licensed by Creative Commons 3.0 for the example icons shown below, and also used as test icons in the testdata folder.

Jupiter

lander

mountains

bus

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultStyle = PathStyle{
	FillOpacity: 1, LineOpacity: 1, LineWidth: 1, MiterLimit: 4, UseNonZeroWinding: true,

	LineCap: rasterx.ButtCap, LineJoin: rasterx.Miter,
	// 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.

Functions

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 SFG color string e.g. #FBD9BD

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 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 computes presentation attributes, class rules and inline style against the current parent, then pushes the element style.

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 any) (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

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

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
	// contains filtered or unexported fields
}

PathStyle holds the state of the SVG style.

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
	Defs         map[string][]definition
	SVGPaths     []SvgPath
	Transform    rasterx.Matrix2D
	// 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 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 the compiled SVG icon into the GraphicContext. All elements should be contained by the Bounds rectangle of the SvgIcon.

func (*SvgIcon) Rasterize

func (s *SvgIcon) Rasterize(width, height int) *image.RGBA

Rasterize renders the SVG into a new, transparent-initialized premultiplied RGBA image. It uses the document's viewBox and preserveAspectRatio, independently of the legacy SetTarget/Transform state. Invalid sizes or an invalid zero-value icon return nil. Images are caller-owned and are never cached by the icon. Concurrent calls are safe while callers do not modify the parsed icon.

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

type SvgPath

type SvgPath struct {
	PathStyle
	Path rasterx.Path
}

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. The path/style remain unchanged; the Dasher is call-local state.

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

Jump to

Keyboard shortcuts

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