oksvg

repository·master·Indexed 41 days ago

https://github.com/srwiley/oksvg

A 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.

Tokens
4.2K
Snippets
20
Records
25
Agent score
51%

What's inside oksvg

  1. Overview of oksvg

    master
    oksvg is a Go-based rasterizer for a partial implementation of the SVG2.0 specification. It is designed to faithfully render a wide variety of SVG icons, though it does not support every single SVG element. It leverages the rasterx package to implement full SVG2.0 path functions, including the newer 'arc' join-mode.
  2. Extra non-standard features in oksvg

    master

    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.
    • Capping and Gaps: Support for extra capping and gap values.
    • Custom Capping: Ability to specify different capping functions for the start and end of lines.
  3. Install dependencies for oksvg

    master

    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/charset

    You must also manually get or clone the rasterx package into your workspace:

    go get github.com/srwiley/rasterx
    go 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/rasterx
  4. Use IconCursor for SVG parsing and style management

    master

    The 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:

    • Style Management: Using PushStyle to manage a stack of PathStyle objects, allowing for nested styling and class adaptation.
    • Gradient Handling: Reading gradient URLs via ReadGradURL and configuring gradient attributes via ReadGradAttr.
    • Element Processing: Handling SVG elements through readStartElement (which dispatches to internal draw functions).
    type IconCursor struct {
    	PathCursor
    	icon                                                 *SvgIcon
    	StyleStack                                           []PathStyle
    	grad                                                 *rasterx.Gradient
    	// ... other internal fields
    }
  5. Push styles onto the IconCursor stack

    master

    The PushStyle method parses SVG style attributes and pushes a new PathStyle onto the StyleStack. It supports:

    • The style attribute (parsing semicolon-separated key:value pairs).
    • The class attribute (applying styles from the icon's class definitions).
    • Direct attributes like 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
    }
  6. Configure gradient attributes with ReadGradAttr

    master

    The ReadGradAttr method applies SVG gradient attributes to the cursor's current gradient object. It supports the following attributes:

    AttributeDescription
    gradientTransformSets the Matrix for the gradient
    gradientUnitsSets units to userSpaceOnUse or objectBoundingBox
    spreadMethodSets 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)
  7. Parse numeric data points with GetPoints

    master

    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")
  8. Parse SVG path strings with PathCursor

    master

    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 representation
  9. Draw an SvgPath with transformations

    master

    To 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)
  10. Replace 'currentColor' in SVG with a specific color using ReadReplacingCurrentColor

    master

    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")
  11. Use SvgIcon to draw icons to a target

    master

    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)
  12. Parse hex color numbers with ParseSVGColorNum

    master

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