svg

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 16 Imported by: 0

README

svg

A clean, efficient SVG rendering library that integrates with the layout engine to produce beautiful SVG graphics from layout trees. Also provides standalone SVG path construction and marker support for data visualization.

Features

  • Layout Integration: Seamlessly renders layout.Node trees to SVG
  • PathBuilder: Fluent API for constructing complex SVG paths with bezier curves
  • Markers: Define custom markers for path endpoints and vertices (arrows, circles, diamonds, etc.)
  • Smooth Curves: Bezier curve interpolation with tension control
  • Basic Shapes: Rect, Circle, Ellipse, Polygon, Polyline, Line, Text
  • Transform Support: Full 2D transform support (translate, rotate, scale, skew)
  • Styling System: Colors, borders, backgrounds, shadows
  • Text Rendering: SVG text elements with proper positioning
  • ClipPath Management: Thread-safe unique ID generation for clipping
  • Gradient Support: Linear and radial gradients with multiple color spaces (OKLCH, OKLAB, sRGB, Display P3)
  • Design Tokens: Themeable styling system

Installation

go get github.com/SCKelemen/svg

Usage

Basic Example
package main

import (
    "fmt"
    "github.com/SCKelemen/layout"
    "github.com/SCKelemen/svg"
)

func main() {
    // Create a layout tree
    root := &layout.Node{
        Style: layout.Style{
            Display: layout.DisplayFlex,
            FlexDirection: layout.FlexDirectionRow,
            Width: 400,
            Height: 200,
        },
        Children: []*layout.Node{
            {Style: layout.Style{Width: 100, Height: 100}},
            {Style: layout.Style{Width: 100, Height: 100}},
        },
    }

    // Perform layout
    constraints := layout.Loose(800, 600)
    layout.Layout(root, constraints, nil)

    // Render to SVG
    output := svg.RenderToSVG(root, svg.Options{
        Width: 400,
        Height: 200,
    })

    fmt.Println(output)
}
With Styling
// Create a styled renderer
renderer := svg.NewRenderer(svg.Options{
    Width: 800,
    Height: 600,
    StyleSheet: svg.DefaultStyles(),
})

// Render with custom styles
output := renderer.Render(root)
Gradients
// Create a gradient with multiple color spaces
gradient := svg.LinearGradient{
    ID: "myGradient",
    X1: 0, Y1: 0,
    X2: 100, Y2: 0,
    Stops: []svg.GradientStop{
        {Offset: "0%", Color: "#3B82F6"},
        {Offset: "100%", Color: "#8B5CF6"},
    },
    ColorSpace: color.GradientOKLCH, // Perceptually uniform gradients
}

// Apply gradient to elements
svgElement := fmt.Sprintf(`<rect fill="url(#myGradient)" x="0" y="0" width="100" height="50"/>`)
PathBuilder - Fluent API for Paths

Create complex SVG paths using a chainable API:

// Build a smooth curved path
points := []svg.Point{
    {X: 50, Y: 200},
    {X: 100, Y: 100},
    {X: 200, Y: 150},
    {X: 300, Y: 50},
}

// Simple polyline
path := svg.PolylinePath(points)

// Smooth bezier curve with tension control
smoothPath := svg.SmoothLinePath(points, 0.3)

// Area chart path (filled region)
areaPath := svg.AreaPath(points, 200) // baseline at y=200

// Smooth area chart
smoothArea := svg.SmoothAreaPath(points, 200, 0.3)

// Manual path construction
pb := svg.NewPathBuilder().
    MoveTo(10, 10).
    LineTo(90, 10).
    CurveTo(120, 10, 120, 40, 90, 40).
    Close()
Markers - Path Decorations

Add markers (arrows, dots, shapes) to path endpoints:

// Create predefined markers
arrow := svg.ArrowMarker("arrow-blue", "#3B82F6")
circle := svg.CircleMarker("dot-green", "#10B981")
diamond := svg.DiamondMarker("diamond-purple", "#8B5CF6")

// Apply markers to a path
pathData := svg.SmoothLinePath(points, 0.3)
decoratedPath := svg.PathWithMarkers(
    pathData,
    svg.Style{Stroke: "#3B82F6", StrokeWidth: 2, Fill: "none"},
    svg.MarkerURL("dot-green"),   // start marker
    "",                            // mid markers (optional)
    svg.MarkerURL("arrow-blue"),  // end marker
)

// Render with markers in defs
output := svg.RenderToSVG(svg.SVGConfig{
    Width: 400, Height: 300,
}, arrow, circle, decoratedPath)

Available marker types:

  • ArrowMarker - Directional arrow
  • CircleMarker - Filled circle
  • SquareMarker - Filled square
  • DiamondMarker - Diamond shape
  • TriangleMarker - Triangle shape
  • CrossMarker - Plus/cross symbol
  • XMarker - X symbol
  • DotMarker - Small dot (customizable radius)

Design Philosophy

This library focuses on:

  1. Simplicity: Clean API with sensible defaults
  2. Integration: First-class support for the layout engine
  3. Extensibility: Easy to add custom rendering logic
  4. Performance: Efficient string building and minimal allocations

Testing

The library includes comprehensive unit tests:

# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

# Run benchmarks
go test -bench=. -benchmem

Coverage: ~50% of statements with tests for PathBuilder, Markers, and core rendering.

Performance

Typical performance on modern hardware:

Operation Time/op Allocations
PolylinePath (100 points) ~2-3 μs Minimal
SmoothLinePath (100 points) ~15-20 μs Moderate
Marker generation ~200-500 ns Low
Full SVG render ~10-50 μs Context-dependent
  • layout - CSS Grid/Flexbox layout engine
  • text - Unicode text handling
  • color - Color space handling
  • cli - Terminal rendering

Documentation

Overview

Package rendersvg provides efficient SVG rendering for layout trees.

This package integrates with github.com/SCKelemen/layout to render computed layout trees as SVG graphics. It supports transforms, styling, text rendering, and clipPath management.

Basic usage:

root := &layout.Node{...}
layout.Layout(root, constraints, nil)
svg := rendersvg.RenderToSVG(root, rendersvg.Options{
	Width: 800,
	Height: 600,
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AreaPath

func AreaPath(points []Point, baselineY float64) string

AreaPath creates a filled area path from points with a baseline

func ArrowMarker

func ArrowMarker(id string, color string) string

ArrowMarker creates a simple arrow marker pointing right

func Circle

func Circle(cx, cy, r float64, style Style) string

Circle renders an SVG circle

func CircleMarker

func CircleMarker(id string, color string) string

CircleMarker creates a circular marker

func CirclePath

func CirclePath(cx, cy, r float64) string

CirclePath creates a circular path using arcs

func CrossMarker

func CrossMarker(id string, color string, strokeWidth float64) string

CrossMarker creates a cross/plus marker

func DiamondMarker

func DiamondMarker(id string, color string) string

DiamondMarker creates a diamond marker

func DotMarker

func DotMarker(id string, color string, radius float64) string

DotMarker creates a small dot marker (good for data points)

func Ellipse

func Ellipse(cx, cy, rx, ry float64, style Style) string

Ellipse renders an SVG ellipse

func EllipsePath

func EllipsePath(cx, cy, rx, ry float64) string

EllipsePath creates an elliptical path using arcs

func Export added in v0.3.0

func Export(svgData string, opts ExportOptions) ([]byte, error)

Export converts SVG to the specified format

func GetFileExtension added in v0.3.0

func GetFileExtension(format ExportFormat) string

GetFileExtension returns the file extension for a format

func GetMimeType added in v0.3.0

func GetMimeType(format ExportFormat) string

GetMimeType returns the MIME type for a format

func GetRectFromNode

func GetRectFromNode(node *layout.Node) layout.Rect

GetRectFromNode extracts the computed rectangle from a layout node

func GetTransformFromNode

func GetTransformFromNode(node *layout.Node) string

GetTransformFromNode extracts SVG transform attribute from a layout node

func GradientURL

func GradientURL(id string) string

GradientURL creates a url() reference to a gradient for use in fill or stroke

func Group

func Group(content string, transform string, style Style) string

Group wraps content in an SVG <g> element with optional transform

func GroupWithClipPath

func GroupWithClipPath(content string, clipPathID string, style Style) string

GroupWithClipPath wraps content in an SVG <g> element with clipPath

func InterpolatedLinearGradient

func InterpolatedLinearGradient(id string, startColor, endColor string, angle float64, steps int, colorSpace color.GradientSpace) (string, error)

InterpolatedLinearGradient creates a linear gradient with color interpolation in the specified color space This creates smooth, natural-looking gradients by interpolating in the chosen color space and converting to sRGB for SVG compatibility. Defaults to OKLCH for perceptually uniform gradients.

colorSpace options:

  • color.GradientRGB: Interpolates in RGB space (fast but not perceptually uniform)
  • color.GradientHSL: Interpolates in HSL space
  • color.GradientLAB: Interpolates in CIE LAB space
  • color.GradientOKLAB: Interpolates in OKLAB space (perceptually uniform)
  • color.GradientLCH: Interpolates in CIE LCH space
  • color.GradientOKLCH: Interpolates in OKLCH space (perceptually uniform, recommended)

func InterpolatedRadialGradient

func InterpolatedRadialGradient(id string, centerColor, edgeColor string, steps int, colorSpace color.GradientSpace) (string, error)

InterpolatedRadialGradient creates a radial gradient with color interpolation in the specified color space This creates smooth, natural-looking gradients by interpolating in the chosen color space and converting to sRGB for SVG compatibility.

colorSpace options: same as InterpolatedLinearGradient

func Line

func Line(x1, y1, x2, y2 float64, style Style) string

Line renders an SVG line

func LineWithMarkers

func LineWithMarkers(x1, y1, x2, y2 float64, style Style, markerStart, markerEnd string) string

LineWithMarkers renders a line with marker references

func LinearGradient

func LinearGradient(def LinearGradientDef) string

LinearGradient creates a linear gradient definition (for use in <defs>)

func Marker

func Marker(def MarkerDef) string

Marker creates a marker definition (for use in <defs>)

func MarkerURL

func MarkerURL(id string) string

MarkerURL creates a url() reference to a marker

func OKLCHLinearGradient

func OKLCHLinearGradient(id string, startColor, endColor string, angle float64, steps int) (string, error)

OKLCHLinearGradient creates a perceptually uniform linear gradient using OKLCH interpolation This is a convenience wrapper around InterpolatedLinearGradient with color.GradientOKLCH

func OKLCHRadialGradient

func OKLCHRadialGradient(id string, centerColor, edgeColor string, steps int) (string, error)

OKLCHRadialGradient creates a perceptually uniform radial gradient using OKLCH interpolation This is a convenience wrapper around InterpolatedRadialGradient with color.GradientOKLCH

func Path

func Path(d string, style Style) string

Path renders an SVG path

func PathWithMarkers

func PathWithMarkers(d string, style Style, markerStart, markerMid, markerEnd string) string

PathWithMarkers renders a path with marker references

func Polygon

func Polygon(points []Point, style Style) string

Polygon renders an SVG polygon (closed shape from points)

func PolygonPath

func PolygonPath(points []Point) string

PolygonPath creates a closed path from multiple points

func Polyline

func Polyline(points []Point, style Style) string

Polyline renders an SVG polyline (open shape from points)

func PolylinePath

func PolylinePath(points []Point) string

PolylinePath creates a path from multiple points (open path)

func PolylineWithMarkers

func PolylineWithMarkers(points []Point, style Style, markerStart, markerMid, markerEnd string) string

PolylineWithMarkers renders a polyline with marker references

func RadialGradient

func RadialGradient(def RadialGradientDef) string

RadialGradient creates a radial gradient definition (for use in <defs>)

func Rect

func Rect(x, y, width, height float64, style Style) string

Rect renders an SVG rectangle

func RectPath

func RectPath(x, y, width, height float64) string

RectPath creates a rectangular path

func RenderNodes

func RenderNodes(nodes []*layout.Node, opts Options) string

RenderNodes renders multiple layout nodes at their computed positions This is useful when you have a collection of already-positioned nodes

func RenderToSVG

func RenderToSVG(root *layout.Node, opts Options) string

RenderToSVG renders a layout tree to an SVG string

func RoundedRect

func RoundedRect(x, y, width, height, rx, ry float64, style Style) string

RoundedRect renders an SVG rectangle with rounded corners

func RoundedRectPath

func RoundedRectPath(x, y, width, height, rx, ry float64) string

RoundedRectPath creates a rounded rectangular path

func SimpleLinearGradient

func SimpleLinearGradient(id string, startColor, endColor string, angle float64) string

SimpleLinearGradient creates a simple two-color linear gradient angle is in degrees (0 = left to right, 90 = bottom to top)

func SimpleRadialGradient

func SimpleRadialGradient(id string, centerColor, edgeColor string) string

SimpleRadialGradient creates a simple two-color radial gradient

func SmoothAreaPath

func SmoothAreaPath(points []Point, baselineY float64, tension float64) string

SmoothAreaPath creates a smooth filled area path from points with a baseline

func SmoothLinePath

func SmoothLinePath(points []Point, tension float64) string

SmoothLinePath creates a smooth curve through points using cubic Bézier curves tension controls how tight the curve is (0 = straight lines, 1 = very curved)

func SquareMarker

func SquareMarker(id string, color string) string

SquareMarker creates a square marker

func TSpan

func TSpan(content string, style Style, dx, dy float64) string

TSpan renders an SVG tspan element (for use inside text elements) TSpan allows styling different parts of text independently

func Text

func Text(content string, x, y float64, style Style) string

Text renders an SVG text element

func TextPath

func TextPath(content string, pathID string, style Style, startOffset string) string

TextPath renders text along a path

func TextWithSpans

func TextWithSpans(x, y float64, style Style, spans []string) string

TextWithSpans renders an SVG text element with multiple styled spans

func TriangleMarker

func TriangleMarker(id string, color string) string

TriangleMarker creates a triangle marker

func URL

func URL(id string) string

URL returns the CSS url() reference for a clipPath ID

func XMarker

func XMarker(id string, color string, strokeWidth float64) string

XMarker creates an X marker

Types

type ClipPath

type ClipPath struct {
	ID   string
	Path string // SVG path or shapes to use for clipping
}

ClipPath represents an SVG clipPath definition

type ClipPathManager

type ClipPathManager struct {
	// contains filtered or unexported fields
}

ClipPathManager manages SVG clipPath definitions and generates unique IDs

func NewClipPathManager

func NewClipPathManager() *ClipPathManager

NewClipPathManager creates a new clipPath manager

func (*ClipPathManager) AddCircle

func (m *ClipPathManager) AddCircle(cx, cy, r float64) string

AddCircle adds a circle clipPath and returns its ID

func (*ClipPathManager) AddCustom

func (m *ClipPathManager) AddCustom(pathContent string) string

AddCustom adds a custom clipPath and returns its ID

func (*ClipPathManager) AddRect

func (m *ClipPathManager) AddRect(x, y, width, height float64) string

AddRect adds a rectangle clipPath and returns its ID

func (*ClipPathManager) AddRoundedRect

func (m *ClipPathManager) AddRoundedRect(x, y, width, height, radius float64) string

AddRoundedRect adds a rounded rectangle clipPath and returns its ID

func (*ClipPathManager) GenerateID

func (m *ClipPathManager) GenerateID() string

GenerateID generates a unique clipPath ID

func (*ClipPathManager) ToSVGDefs

func (m *ClipPathManager) ToSVGDefs() string

ToSVGDefs converts all clipPaths to SVG <defs> content

type DominantBaseline

type DominantBaseline string

DominantBaseline defines vertical text alignment

const (
	DominantBaselineAuto         DominantBaseline = "auto"
	DominantBaselineMiddle       DominantBaseline = "middle"
	DominantBaselineHanging      DominantBaseline = "hanging"
	DominantBaselineTextTop      DominantBaseline = "text-top"
	DominantBaselineTextBottom   DominantBaseline = "text-bottom"
	DominantBaselineAlphabetic   DominantBaseline = "alphabetic"
	DominantBaselineMathematical DominantBaseline = "mathematical"
)

type ExportFormat added in v0.3.0

type ExportFormat string

ExportFormat represents an export format

const (
	// FormatSVG exports as SVG (passthrough)
	FormatSVG ExportFormat = "svg"
	// FormatPNG exports as PNG
	FormatPNG ExportFormat = "png"
	// FormatJPEG exports as JPEG
	FormatJPEG ExportFormat = "jpeg"
)

func ParseFormat added in v0.3.0

func ParseFormat(s string) (ExportFormat, error)

ParseFormat parses a format string

type ExportOptions added in v0.3.0

type ExportOptions struct {
	Format  ExportFormat
	Width   int // For raster formats, 0 = use SVG dimensions
	Height  int // For raster formats, 0 = use SVG dimensions
	Quality int // For JPEG, 0-100 (default 90)
	DPI     int // Dots per inch (default 96)
}

ExportOptions configures export settings

func DefaultExportOptions added in v0.3.0

func DefaultExportOptions() ExportOptions

DefaultExportOptions returns sensible defaults

type FontStyle

type FontStyle string

FontStyle defines font style values

const (
	FontStyleNormal  FontStyle = "normal"
	FontStyleItalic  FontStyle = "italic"
	FontStyleOblique FontStyle = "oblique"
)

type FontWeight

type FontWeight string

FontWeight defines font weight values

const (
	FontWeightNormal  FontWeight = "normal"
	FontWeightBold    FontWeight = "bold"
	FontWeightBolder  FontWeight = "bolder"
	FontWeightLighter FontWeight = "lighter"
	FontWeight100     FontWeight = "100"
	FontWeight200     FontWeight = "200"
	FontWeight300     FontWeight = "300"
	FontWeight400     FontWeight = "400"
	FontWeight500     FontWeight = "500"
	FontWeight600     FontWeight = "600"
	FontWeight700     FontWeight = "700"
	FontWeight800     FontWeight = "800"
	FontWeight900     FontWeight = "900"
)

type GradientSpreadMethod

type GradientSpreadMethod string

GradientSpreadMethod defines how gradient fills outside its bounds

const (
	GradientSpreadPad     GradientSpreadMethod = "pad"
	GradientSpreadReflect GradientSpreadMethod = "reflect"
	GradientSpreadRepeat  GradientSpreadMethod = "repeat"
)

type GradientStop

type GradientStop struct {
	Offset  string // percentage or decimal (e.g., "0%", "50%", "1.0")
	Color   string // color value (hex, rgb, etc.)
	Opacity float64
}

GradientStop represents a color stop in a gradient

type GradientUnits

type GradientUnits string

GradientUnits defines the coordinate system for gradients

const (
	GradientUnitsUserSpaceOnUse    GradientUnits = "userSpaceOnUse"
	GradientUnitsObjectBoundingBox GradientUnits = "objectBoundingBox"
)

type LinearGradientDef

type LinearGradientDef struct {
	ID           string
	X1, Y1       string // Start point (can be percentage or absolute)
	X2, Y2       string // End point (can be percentage or absolute)
	Stops        []GradientStop
	Units        GradientUnits
	SpreadMethod GradientSpreadMethod
}

LinearGradientDef represents a linear gradient definition

type MarkerDef

type MarkerDef struct {
	ID           string
	ViewBox      string       // e.g., "0 0 10 10"
	RefX         float64      // Reference point X
	RefY         float64      // Reference point Y
	MarkerWidth  float64      // Width of marker viewport
	MarkerHeight float64      // Height of marker viewport
	Orient       MarkerOrient // auto, auto-start-reverse, or angle
	MarkerUnits  MarkerUnits
	Content      string // SVG content inside the marker
}

MarkerDef represents a marker definition

type MarkerOrient

type MarkerOrient string

MarkerOrient defines the orientation of a marker

const (
	MarkerOrientAuto      MarkerOrient = "auto"
	MarkerOrientAutoStart MarkerOrient = "auto-start-reverse"
)

type MarkerStyle

type MarkerStyle struct {
	MarkerStart string // URL reference to marker for start of path
	MarkerMid   string // URL reference to marker for middle vertices
	MarkerEnd   string // URL reference to marker for end of path
}

MarkerStyle represents marker styling that can be added to a Style struct

type MarkerUnits

type MarkerUnits string

MarkerUnits defines the coordinate system for marker dimensions

const (
	MarkerUnitsStrokeWidth    MarkerUnits = "strokeWidth"
	MarkerUnitsUserSpaceOnUse MarkerUnits = "userSpaceOnUse"
)

type Options

type Options struct {
	// Width of the output SVG
	Width float64

	// Height of the output SVG
	Height float64

	// ViewBox specifies a custom viewBox attribute (optional)
	// If empty, uses "0 0 {Width} {Height}"
	ViewBox string

	// StyleSheet to include in the SVG (optional)
	StyleSheet *StyleSheet

	// IncludeXMLDeclaration includes <?xml...?> declaration
	IncludeXMLDeclaration bool

	// Namespace adds xmlns attribute to <svg>
	Namespace bool

	// PreserveAspectRatio sets the preserveAspectRatio attribute
	PreserveAspectRatio string

	// BackgroundColor sets a background rectangle (optional)
	BackgroundColor string

	// StyleFunc allows custom styling per node
	// Called for each node with the node and its depth in the tree
	StyleFunc func(node interface{}, depth int) Style

	// RenderFunc allows custom rendering per node type
	// If it returns non-empty string, that's used instead of default rendering
	RenderFunc func(node interface{}, depth int) string
}

Options configures SVG rendering behavior

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns sensible default options

func WithSize

func WithSize(width, height float64) Options

WithSize creates options with specified dimensions

func WithStyleSheet

func WithStyleSheet(stylesheet *StyleSheet) Options

WithStyleSheet creates options with a custom stylesheet

type PathBuilder

type PathBuilder struct {
	// contains filtered or unexported fields
}

PathBuilder provides a fluent API for constructing SVG path data

func NewPathBuilder

func NewPathBuilder() *PathBuilder

NewPathBuilder creates a new path builder

func (*PathBuilder) ArcTo

func (pb *PathBuilder) ArcTo(rx, ry, xAxisRotation float64, largeArcFlag, sweepFlag int, x, y float64) *PathBuilder

ArcTo draws an elliptical arc rx, ry: x and y radius xAxisRotation: rotation of the ellipse in degrees largeArcFlag: 0 for small arc, 1 for large arc sweepFlag: 0 for counter-clockwise, 1 for clockwise x, y: end point

func (*PathBuilder) Build

func (pb *PathBuilder) Build() string

Build returns the path data string (alias for String)

func (*PathBuilder) Close

func (pb *PathBuilder) Close() *PathBuilder

Close closes the current path by drawing a line back to the first point

func (*PathBuilder) CurveTo

func (pb *PathBuilder) CurveTo(x1, y1, x2, y2, x, y float64) *PathBuilder

CurveTo draws a cubic Bézier curve

func (*PathBuilder) HorizontalLineTo

func (pb *PathBuilder) HorizontalLineTo(x float64) *PathBuilder

HorizontalLineTo draws a horizontal line to the specified x coordinate

func (*PathBuilder) LineTo

func (pb *PathBuilder) LineTo(x, y float64) *PathBuilder

LineTo draws a line from the current point to the specified point

func (*PathBuilder) MoveTo

func (pb *PathBuilder) MoveTo(x, y float64) *PathBuilder

MoveTo moves the pen to the specified point without drawing

func (*PathBuilder) QuadraticCurveTo

func (pb *PathBuilder) QuadraticCurveTo(x1, y1, x, y float64) *PathBuilder

QuadraticCurveTo draws a quadratic Bézier curve

func (*PathBuilder) Reset

func (pb *PathBuilder) Reset() *PathBuilder

Reset clears the path builder for reuse

func (*PathBuilder) SmoothCurveTo

func (pb *PathBuilder) SmoothCurveTo(x2, y2, x, y float64) *PathBuilder

SmoothCurveTo draws a smooth cubic Bézier curve (first control point is reflection of previous)

func (*PathBuilder) SmoothQuadraticCurveTo

func (pb *PathBuilder) SmoothQuadraticCurveTo(x, y float64) *PathBuilder

SmoothQuadraticCurveTo draws a smooth quadratic Bézier curve

func (*PathBuilder) String

func (pb *PathBuilder) String() string

String returns the path data string

func (*PathBuilder) VerticalLineTo

func (pb *PathBuilder) VerticalLineTo(y float64) *PathBuilder

VerticalLineTo draws a vertical line to the specified y coordinate

type Point

type Point struct {
	X, Y float64
}

Point represents a 2D point

type RadialGradientDef

type RadialGradientDef struct {
	ID           string
	CX, CY       string // Center point (can be percentage or absolute)
	R            string // Radius (can be percentage or absolute)
	FX, FY       string // Focal point (optional, defaults to center)
	FR           string // Focal radius (optional)
	Stops        []GradientStop
	Units        GradientUnits
	SpreadMethod GradientSpreadMethod
}

RadialGradientDef represents a radial gradient definition

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer renders layout trees to SVG

func NewRenderer

func NewRenderer(opts Options) *Renderer

NewRenderer creates a new SVG renderer with the given options

func (*Renderer) GetClipPathManager

func (r *Renderer) GetClipPathManager() *ClipPathManager

GetClipPathManager returns the clipPath manager for custom clipPath creation

func (*Renderer) Render

func (r *Renderer) Render(root *layout.Node) string

Render renders the layout tree to SVG

func (*Renderer) SetDefaultStyle

func (r *Renderer) SetDefaultStyle(style Style)

SetDefaultStyle sets the default style for rendered nodes

type StrokeLinecap

type StrokeLinecap string

StrokeLinecap defines how the end of a stroke is rendered

const (
	StrokeLinecapButt   StrokeLinecap = "butt"
	StrokeLinecapRound  StrokeLinecap = "round"
	StrokeLinecapSquare StrokeLinecap = "square"
)

type StrokeLinejoin

type StrokeLinejoin string

StrokeLinejoin defines how corners of a stroke are rendered

const (
	StrokeLinejoinMiter StrokeLinejoin = "miter"
	StrokeLinejoinRound StrokeLinejoin = "round"
	StrokeLinejoinBevel StrokeLinejoin = "bevel"
)

type Style

type Style struct {
	Fill             string
	Stroke           string
	StrokeWidth      float64
	StrokeDashArray  string // Dash pattern, e.g. "5,5" or "10,5,2,5"
	StrokeLinecap    StrokeLinecap
	StrokeLinejoin   StrokeLinejoin
	Opacity          float64
	FillOpacity      float64
	StrokeOpacity    float64
	Class            string
	ClipPath         string
	TextAnchor       TextAnchor
	DominantBaseline DominantBaseline
	FontFamily       string
	FontSize         units.Length // Type-safe CSS length with units
	FontWeight       FontWeight
	FontStyle        FontStyle
}

Style represents styling attributes for SVG elements

func StyleWithMarkers

func StyleWithMarkers(style Style, markers MarkerStyle) Style

StyleWithMarkers extends a Style with marker references

type StyleRule

type StyleRule struct {
	Selector   string
	Properties map[string]string
}

StyleRule represents a single CSS rule

type StyleSheet

type StyleSheet struct {
	Rules []StyleRule
}

StyleSheet represents a collection of CSS styles for SVG rendering

func DefaultStyleSheet

func DefaultStyleSheet() *StyleSheet

DefaultStyleSheet returns a sensible default stylesheet for SVG rendering

func (*StyleSheet) AddRule

func (ss *StyleSheet) AddRule(selector string, properties map[string]string)

AddRule adds a custom CSS rule to the stylesheet

func (*StyleSheet) ToSVG

func (ss *StyleSheet) ToSVG() string

ToSVG converts the stylesheet to SVG <style> element

type TextAnchor

type TextAnchor string

TextAnchor defines horizontal text alignment

const (
	TextAnchorStart  TextAnchor = "start"
	TextAnchorMiddle TextAnchor = "middle"
	TextAnchorEnd    TextAnchor = "end"
)

Directories

Path Synopsis
examples
basic command
tier1_features command

Jump to

Keyboard shortcuts

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