Overview of oksvg
masterrasterx package to implement full SVG2.0 path functions, including the newer 'arc' join-mode.repository·master·Indexed 41 days ago
https://github.com/srwiley/oksvgA Go library for rasterizing SVG files into images, featuring a partial implementation of the SVG2.0 specification. It is designed for rendering SVG icons and leverages the rasterx package to support full SVG2.0 path functions, including the 'arc' join-mode, arc-clip, and custom capping functions.
rasterx package to implement full SVG2.0 path functions, including the newer 'arc' join-mode.Beyond standard SVG2.0 support, oksvg provides several non-standard features for path rendering:
arc join-mode: Supported via the underlying rasterx engine.arc-clip: An arc analog to miter-clip.To use oksvg, you must install several non-standard Go library dependencies and ensure the rasterx package is available in your workspace.
Run the following commands to fetch the required x/ packages:
go get golang.org/x/image/math/fixed
go get golang.org/x/image/colornames
go get golang.org/x/net/html/charsetYou must also manually get or clone the rasterx package into your workspace:
go get github.com/srwiley/rasterxgo get golang.org/x/image/math/fixed
go get golang.org/x/image/colornames
go get golang.org/x/net/html/charset
go get github.com/srwiley/rasterxThe IconCursor struct is the primary tool used during the parsing of SVG files. It manages the state of the parser, including the current path, the style stack for CSS-like inheritance, and definitions (like gradients).
Key responsibilities include:
PushStyle to manage a stack of PathStyle objects, allowing for nested styling and class adaptation.ReadGradURL and configuring gradient attributes via ReadGradAttr.readStartElement (which dispatches to internal draw functions).type IconCursor struct {
PathCursor
icon *SvgIcon
StyleStack []PathStyle
grad *rasterx.Gradient
// ... other internal fields
}The PushStyle method parses SVG style attributes and pushes a new PathStyle onto the StyleStack. It supports:
style attribute (parsing semicolon-separated key:value pairs).class attribute (applying styles from the icon's class definitions).fill, stroke, and opacity.When a new style is pushed, it inherits the properties of the current top style on the stack, allowing for nested style overrides.
// attrs are the xml.Attr slice from the current SVG element
err := cursor.PushStyle(attrs)
if err != nil {
// handle error
}The ReadGradAttr method applies SVG gradient attributes to the cursor's current gradient object. It supports the following attributes:
| Attribute | Description |
|---|---|
gradientTransform | Sets the Matrix for the gradient |
gradientUnits | Sets units to userSpaceOnUse or objectBoundingBox |
spreadMethod | Sets spread to pad, reflect, or repeat |
This method modifies the c.grad field directly.
// attr is an xml.Attr from the SVG parser
err := cursor.ReadGradAttr(attr)The GetPoints method reads a string containing floating-point numbers (in SVG format) and appends them to the PathCursor's internal points slice. It handles various SVG number formats, including scientific notation and negative numbers. This method clears the existing points slice before reading new data.
err := cursor.GetPoints("10.5 -20.3 30e-1")The PathCursor struct is used to translate SVG path description strings into a rasterx.Path. It embeds rasterx.Path and provides the CompilePath method to process a full SVG path string.
When calling CompilePath, the cursor initializes its state, parses the commands (like M, L, C, etc.), and converts them into equivalent rasterx path commands.
You can control how the parser handles unknown SVG commands using the ErrorMode field:
IgnoreErrorMode: Skips unparsed elements (default).WarnErrorMode: Outputs a warning when an unparsed element is found.StrictErrorMode: Returns an error when an unparsed element is found.import "github.com/srwiley/oksvg"
// ... setup rasterx path ...
cursor := &oksvg.PathCursor{
// ErrorMode can be set to oksvg.StrictErrorMode, etc.
ErrorMode: oksvg.StrictErrorMode,
}
err := cursor.CompilePath("M 10 10 L 50 50 Z")
if err != nil {
// handle error
}
// cursor.Path now contains the rasterx.Path representationTo apply a transformation (like scaling, rotation, or translation) when drawing an SvgPath, use the DrawTransformed method. This method applies the provided rasterx.Matrix2D to the path's internal matrix adder.
Note that DrawTransformed temporarily modifies the path's internal matrix and restores it after the operation is complete.
// Assuming 't' is a rasterx.Matrix2D
svgp.DrawTransformed(r, 1.0, t)Use ReadReplacingCurrentColor to load an SVG icon while simultaneously replacing all instances of the CSS currentColor keyword with a specific color value. This is useful for dynamically changing icon colors.
The currentColor argument must be a valid color string (e.g., hex #FF0000, rgb(255,0,0), or a named color like red).
// Replaces 'currentColor' with red
icon, err := oksvg.ReadReplacingCurrentColor(stream, "red")The SvgIcon type holds data parsed from an SVG, including its ViewBox, SVGPaths, and Transform matrix. You can use it to render an icon into a rasterx.Dasher context.
To ensure the icon is drawn at a specific size and position, use SetTarget(x, y, w, h) first. This calculates the necessary transformation matrix to map the SVG's internal coordinate system (the ViewBox) to the desired rectangle in your target coordinate space. After setting the target, call Draw(r, opacity) to perform the actual rendering.
// Assuming 'icon' is a pointer to an initialized SvgIcon
// and 'dasher' is a pointer to a rasterx.Dasher
// 1. Define the target area (x, y, width, height) where the icon should appear
icon.SetTarget(0, 0, 100, 100)
// 2. Draw the icon with a specific opacity (e.g., 1.0 for full opacity)
icon.Draw(dasher, 1.0)Use ParseSVGColorNum to parse a hex color string (e.g., #FBD9BD or #FBD) into its individual Red, Green, and Blue uint8 components.
r, g, b, err := oksvg.ParseSVGColorNum("#FBD9BD")