oksvg

package module
v0.0.0-...-87f9155 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: BSD-3-Clause Imports: 16 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

Maintenance note. The refactor in this fork was carried out by DSH (DeepSeek Harness, deepseek-flash), an AI coding agent: twelve independent commits, each with its own regression test, none of them squashed. Upstream has not been touched since 2022-10-11, so this fork is where the fixes live. CHANGELOG.md lists every change, and every one of them that a user can see in the output.

oksvg

oksvg is a rasterizer for a partial implementation of the SVG2.0 specification in golang.

It continues srwiley/oksvg, which stopped being maintained in 2022. The exported API is the same except for two additions, so moving to this fork costs one line and no change to your code.

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.

oksvg uses the rasterx rasterizer package which implements full SVG2.0 path functions, including the newer 'arc' join-mode.

arcs and caps

Using this fork

Go 1.18 or later. The module path is the fork's own:

import "github.com/Drelf2018/oksvg"

To keep the import path you already have instead, add one line to go.mod and change no code at all:

require github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c

replace github.com/srwiley/oksvg => github.com/Drelf2018/oksvg <version>

<version> is the tag or pseudo-version you want to pin. A checkout works just as well, which is handy while reviewing:

replace github.com/srwiley/oksvg => ../oksvg

What this fork changes

The details are in CHANGELOG.md. In short:

Cases that end the process, which is what a renderer cannot live with:

  • rgb(,,) or hsl(0,,) in a color attribute panicked with an index out of range. ParseSVGColor was rewritten, and it also stopped quietly misreading hsl(0,50,50) as a nearly black color.
  • A <use> element that referred to itself recursed until the goroutine stack was exhausted. A stack overflow is fatal and cannot be recovered from.

Wrong output:

  • The stroke width, the dash pattern and the dash offset did not follow the scale of the drawing, so an icon whose intrinsic size differs from its view box was stroked far too thick or invisibly thin.
  • transform="scale(sx)" scaled y by 0, which collapsed everything inside it onto the x axis.
  • An icon sized width="100%" came out blank: the unreadable length ended the attribute loop before the view box behind it was read, and SetTarget divided by the zero size left over.
  • A gradient, or a definition named by a <use>, that was declared later in the document was not resolved. The document is read twice now, so where a definition sits no longer matters.
  • StrictErrorMode only ever reported unknown elements; the errors of known elements were dropped on the way out. It reports them now.
  • The initial line width was 2 and the initial line join was bevel, where SVG 2 says 1 and miter.

Added:

  • Rectangle, the type of SvgIcon.ViewBox, which used to be an anonymous struct no caller could name, and SvgIcon.SetViewBox to set it in one call.
  • A fuzz target for ReadIconStream.

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.

Jupiter

lander

mountains

bus

Non-standard library dependencies

oksvg requires the following imports which are not included in the go standard library:

  • golang.org/x/net/html/charset
  • golang.org/x/image/colornames
  • golang.org/x/image/math/fixed

Go modules resolve them, nothing has to be fetched by hand. oksvg also requires the rasterx package, which lives here:

  • github.com/srwiley/rasterx

Tests

This repository keeps no tests. Implementation and test code are kept apart on purpose here: what is published is the library, and the tests that go with it are run from a working copy instead. They are not part of the module, so a clone carries none of them.

License

BSD 3-Clause, see LICENSE. Copyright (c) 2018, Steven R Wiley.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultStyle = PathStyle{1.0, 1.0, 1.0, 0.0, 4.0, nil, true,
	color.NRGBA{0x00, 0x00, 0x00, 0xff}, nil,
	nil, nil, rasterx.ButtCap, rasterx.Miter, rasterx.MatrixAdder{M: rasterx.Identity}}

DefaultStyle sets the default PathStyle to the initial values of SVG 2: fill black with the nonzero winding rule, full opacity, no stroke, a line width of 1, a miter limit of 4, and ButtCap line ends with Miter line joins.

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 parses the style element, and push it on the style stack. Only color and opacity are supported for fill. Note that this parses both the contents of a style attribute plus direct fill and opacity attributes.

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

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

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 Rectangle

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

Rectangle is a rectangle in user space. It is the type of SvgIcon.ViewBox, and its layout matches the bounds of a rasterx.Gradient, so that the two can be assigned to one another without moving the fields across one by one.

type SvgIcon

type SvgIcon struct {
	ViewBox      Rectangle
	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. Only the first ErrorMode value is used; any additional values are ignored.

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) SetTarget

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

SetTarget sets the Transform matrix to draw within the bounds of the rectangle arguments

func (*SvgIcon) SetViewBox

func (s *SvgIcon) SetViewBox(b Rectangle)

SetViewBox sets the view box of the icon, the user space the icon is drawn in. SetTarget scales that space to the target rectangle.

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.

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
⌂ 换网址