svg

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2024 License: BSD-3-Clause Imports: 37 Imported by: 4

README

svg

SVG implements the Scalable Vector Graphics standard, rendering onto a Go standard image bitmap.

svg cli

Cogent Core provides a helpful command line tool for rendering and creating svg files. To install it, run:

go install cogentcore.org/core/svg/cmd/svg@main

Example usage:

# Render an svg file
svg icon.svg 250
# Embed an image into an svg file
svg embed-image image.png

Documentation

Overview

Package svg provides SVG rendering classes, I/O parsing: full SVG rendering

SVG currently supports most of SVG, but not:

  • Flow
  • Filter Effects
  • 3D Perspective transforms

See gi/examples/svg for a basic SVG viewer app, using the svg.Editor, which will ultimately be expanded to support more advanced editing. Also in that directory are a number of test files that stress different aspects of rendering.

svg.NodeBase is the base type for all SVG elements -- unlike Widget nodes, SVG nodes do not use layout logic, and just draw directly into a parent SVG viewport, with cumulative transforms determining drawing position, etc. The BBox values are only valid after rendering for these nodes.

It uses srwiley/rasterx for SVG-compatible rasterization, and the core.Paint interface for drawing.

The Path element uses a compiled bytecode version of the Data path for increased speed.

Index

Constants

View Source
const SVGRefCountKey = "SVGRefCount"

Variables

View Source
var CircleType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Circle", IDName: "circle", Doc: "Circle is a SVG circle", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Pos", Doc: "position of the center of the circle"}, {Name: "Radius", Doc: "radius of the circle"}}, Instance: &Circle{}})

CircleType is the types.Type for Circle

View Source
var ClipPathType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.ClipPath", IDName: "clip-path", Doc: "ClipPath is used for holding a path that renders as a clip path", Embeds: []types.Field{{Name: "NodeBase"}}, Instance: &ClipPath{}})

ClipPathType is the types.Type for ClipPath

View Source
var EllipseType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Ellipse", IDName: "ellipse", Doc: "Ellipse is a SVG ellipse", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Pos", Doc: "position of the center of the ellipse"}, {Name: "Radii", Doc: "radii of the ellipse in the horizontal, vertical axes"}}, Instance: &Ellipse{}})

EllipseType is the types.Type for Ellipse

View Source
var FilterType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Filter", IDName: "filter", Doc: "Filter represents SVG filter* elements", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "FilterType"}}, Instance: &Filter{}})

FilterType is the types.Type for Filter

View Source
var FlowType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Flow", IDName: "flow", Doc: "Flow represents SVG flow* elements", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "FlowType"}}, Instance: &Flow{}})

FlowType is the types.Type for Flow

View Source
var GradientType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Gradient", IDName: "gradient", Doc: "Gradient is used for holding a specified color gradient.\nThe name is the id for lookup in url", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Grad", Doc: "the color gradient"}, {Name: "StopsName", Doc: "name of another gradient to get stops from"}}, Instance: &Gradient{}})

GradientType is the types.Type for Gradient

View Source
var GroupType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Group", IDName: "group", Doc: "Group groups together SVG elements.\nProvides a common transform for all group elements\nand shared style properties.", Embeds: []types.Field{{Name: "NodeBase"}}, Instance: &Group{}})

GroupType is the types.Type for Group

View Source
var ImageType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Image", IDName: "image", Doc: "Image is an SVG image (bitmap)", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Pos", Doc: "position of the top-left of the image"}, {Name: "Size", Doc: "rendered size of the image (imposes a scaling on image when it is rendered)"}, {Name: "Filename", Doc: "file name of image loaded -- set by OpenImage"}, {Name: "ViewBox", Doc: "how to scale and align the image"}, {Name: "Pixels", Doc: "the image pixels"}}, Instance: &Image{}})

ImageType is the types.Type for Image

View Source
var InkscapeProperties = map[string]bool{
	"isstock": true,
	"stockid": true,
}

InkscapeProperties are property keys that should be prefixed with "inkscape:"

View Source
var LineType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Line", IDName: "line", Doc: "Line is a SVG line", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Start", Doc: "position of the start of the line"}, {Name: "End", Doc: "position of the end of the line"}}, Instance: &Line{}})

LineType is the types.Type for Line

View Source
var MarkerType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Marker", IDName: "marker", Doc: "Marker represents marker elements that can be drawn along paths (arrow heads, etc)", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "RefPos", Doc: "reference position to align the vertex position with, specified in ViewBox coordinates"}, {Name: "Size", Doc: "size of marker to render, in Units units"}, {Name: "Units", Doc: "units to use"}, {Name: "ViewBox", Doc: "viewbox defines the internal coordinate system for the drawing elements within the marker"}, {Name: "Orient", Doc: "orientation of the marker -- either 'auto' or an angle"}, {Name: "VertexPos", Doc: "current vertex position"}, {Name: "VertexAngle", Doc: "current vertex angle in radians"}, {Name: "StrokeWidth", Doc: "current stroke width"}, {Name: "Transform", Doc: "net transform computed from settings and current values -- applied prior to rendering"}, {Name: "EffSize", Doc: "effective size for actual rendering"}}, Instance: &Marker{}})

MarkerType is the types.Type for Marker

View Source
var MetaDataType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.MetaData", IDName: "meta-data", Doc: "MetaData is used for holding meta data info", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "MetaData"}}, Instance: &MetaData{}})

MetaDataType is the types.Type for MetaData

View Source
var NodeBaseType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.NodeBase", IDName: "node-base", Doc: "svg.NodeBase is the base type for elements within the SVG scenegraph", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Class", Doc: "user-defined class name(s) used primarily for attaching\nCSS styles to different display elements.\nMultiple class names can be used to combine properties:\nuse spaces to separate per css standard."}, {Name: "CSS", Doc: "CSS is the cascading style sheet at this level.\nThese styles apply here and to everything below, until superceded.\nUse .class and #name Properties elements to apply entire styles\nto given elements, and type for element type."}, {Name: "CSSAgg", Doc: "CSSAgg is the aggregated css properties from all higher nodes down to this node."}, {Name: "BBox", Doc: "bounding box for the node within the SVG Pixels image.\nThis one can be outside the visible range of the SVG image.\nVisBBox is intersected and only shows visible portion."}, {Name: "VisBBox", Doc: "visible bounding box for the node intersected with the SVG image geometry"}, {Name: "Paint", Doc: "paint style information for this node"}}, Instance: &NodeBase{}})

NodeBaseType is the types.Type for NodeBase

View Source
var PathCmdNMap = map[PathCmds]int{
	PcM: 2,
	Pcm: 2,
	PcL: 2,
	Pcl: 2,
	PcH: 1,
	Pch: 1,
	PcV: 1,
	Pcv: 1,
	PcC: 6,
	Pcc: 6,
	PcS: 4,
	Pcs: 4,
	PcQ: 4,
	Pcq: 4,
	PcT: 2,
	Pct: 2,
	PcA: 7,
	Pca: 7,
	PcZ: 0,
	Pcz: 0,
}

PathCmdNMap gives the number of points per each command

View Source
var PathCmdToRune = map[PathCmds]rune{}

PathCmdToRune maps command to rune

View Source
var PathRuneToCmd = map[rune]PathCmds{
	'M': PcM,
	'm': Pcm,
	'L': PcL,
	'l': Pcl,
	'H': PcH,
	'h': Pch,
	'V': PcV,
	'v': Pcv,
	'C': PcC,
	'c': Pcc,
	'S': PcS,
	's': Pcs,
	'Q': PcQ,
	'q': Pcq,
	'T': PcT,
	't': Pct,
	'A': PcA,
	'a': Pca,
	'Z': PcZ,
	'z': Pcz,
}

PathRuneToCmd maps rune to path command

View Source
var PathType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Path", IDName: "path", Doc: "Path renders SVG data sequences that can render just about anything", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Data", Doc: "the path data to render -- path commands and numbers are serialized, with each command specifying the number of floating-point coord data points that follow"}, {Name: "DataStr", Doc: "string version of the path data"}}, Instance: &Path{}})

PathType is the types.Type for Path

View Source
var PolygonType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Polygon", IDName: "polygon", Doc: "Polygon is a SVG polygon", Embeds: []types.Field{{Name: "Polyline"}}, Instance: &Polygon{}})

PolygonType is the types.Type for Polygon

View Source
var PolylineType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Polyline", IDName: "polyline", Doc: "Polyline is a SVG multi-line shape", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Points", Doc: "the coordinates to draw -- does a moveto on the first, then lineto for all the rest"}}, Instance: &Polyline{}})

PolylineType is the types.Type for Polyline

View Source
var RectType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Rect", IDName: "rect", Doc: "Rect is a SVG rectangle, optionally with rounded corners", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Pos", Doc: "position of the top-left of the rectangle"}, {Name: "Size", Doc: "size of the rectangle"}, {Name: "Radius", Doc: "radii for curved corners, as a proportion of width, height"}}, Instance: &Rect{}})

RectType is the types.Type for Rect

View Source
var SVGNodeType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.SVGNode", IDName: "svg-node", Doc: "SVGNode represents the root of an SVG tree", Embeds: []types.Field{{Name: "Group"}}, Fields: []types.Field{{Name: "ViewBox", Doc: "viewbox defines the coordinate system for the drawing.\nThese units are mapped into the screen space allocated\nfor the SVG during rendering"}}, Instance: &SVGNode{}})

SVGNodeType is the types.Type for SVGNode

View Source
var StyleSheetType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.StyleSheet", IDName: "style-sheet", Doc: "StyleSheet is a Node2D node that contains a stylesheet -- property values\ncontained in this sheet can be transformed into tree.Properties and set in CSS\nfield of appropriate node", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Sheet"}}, Instance: &StyleSheet{}})

StyleSheetType is the types.Type for StyleSheet

View Source
var TextType = types.AddType(&types.Type{Name: "cogentcore.org/core/svg.Text", IDName: "text", Doc: "Text renders SVG text, handling both text and tspan elements.\ntspan is nested under a parent text -- text has empty Text string.", Embeds: []types.Field{{Name: "NodeBase"}}, Fields: []types.Field{{Name: "Pos", Doc: "position of the left, baseline of the text"}, {Name: "Width", Doc: "width of text to render if using word-wrapping"}, {Name: "Text", Doc: "text string to render"}, {Name: "TextRender", Doc: "render version of text"}, {Name: "CharPosX", Doc: "character positions along X axis, if specified"}, {Name: "CharPosY", Doc: "character positions along Y axis, if specified"}, {Name: "CharPosDX", Doc: "character delta-positions along X axis, if specified"}, {Name: "CharPosDY", Doc: "character delta-positions along Y axis, if specified"}, {Name: "CharRots", Doc: "character rotations, if specified"}, {Name: "TextLength", Doc: "author's computed text length, if specified -- we attempt to match"}, {Name: "AdjustGlyphs", Doc: "in attempting to match TextLength, should we adjust glyphs in addition to spacing?"}, {Name: "LastPos", Doc: "last text render position -- lower-left baseline of start"}, {Name: "LastBBox", Doc: "last actual bounding box in display units (dots)"}}, Instance: &Text{}})

TextType is the types.Type for Text

Functions

func AggCSS

func AggCSS(agg *map[string]any, css map[string]any)

AggCSS aggregates css properties

func BBoxFromChildren

func BBoxFromChildren(n Node) image.Rectangle

BBoxFromChildren sets the Group BBox from children

func EscapeText

func EscapeText(w io.Writer, s []byte, escapeNewline bool) error

XMLEscapeText writes to w the properly escaped XML equivalent of the plain text data s. If escapeNewline is true, newline XMLcharacters will be escaped.

func GradientReadPts

func GradientReadPts(gr gradient.Gradient, dat []float32)

GradientReadPoints reads the gradient points from a slice of floating point numbers, reading from the end.

func GradientWritePts

func GradientWritePts(gr gradient.Gradient, dat *[]float32)

GradientWritePoints writes the gradient points to a slice of floating point numbers, appending to end of slice.

func IncRefCount

func IncRefCount(k tree.Node)

func NameFromURL

func NameFromURL(url string) string

NameFromURL returns just the name referred to in a url(#name) if it is not a url(#) format then returns empty string.

func NameID added in v0.0.7

func NameID(nm string, id int) string

NameID returns the name with given unique id. returns plain name if id == 0

func NameToURL

func NameToURL(nm string) string

NameToURL returns url as: url(#name)

func NodePropURL

func NodePropURL(n Node, prop string) string

NodePropURL returns a url(#name) url from given prop name on node, or empty string if none. Returned value is just the 'name' part of the url, not the full string.

func PathCmdIsRel

func PathCmdIsRel(pc PathCmds) bool

PathCmdIsRel returns true if the path command is relative, false for absolute

func PathDataBBox

func PathDataBBox(data []PathData) math32.Box2

PathDataBBox traverses the path data and extracts the local bounding box

func PathDataEnd

func PathDataEnd(data []PathData) (vec math32.Vector2, ang float32)

PathDataEnd gets the ending coords and angle from the path

func PathDataIterFunc

func PathDataIterFunc(data []PathData, fun func(idx int, cmd PathCmds, ptIndex int, cp math32.Vector2, ctrls []math32.Vector2) bool)

PathDataIterFunc traverses the path data and calls given function on each coordinate point, passing overall starting index of coords in data stream, command, index of the points within that command, and coord values (absolute, not relative, regardless of the command type), including special control points for path commands that have them (else nil). If function returns false (use tree.Break vs. tree.Continue) then traversal is aborted. For Control points, order is in same order as in standard path stream when multiple, e.g., C,S. For A: order is: nc, prv, rad, math32.Vector2{X: ang}, math32.Vec2(laf, sf)}

func PathDataNext

func PathDataNext(data []PathData, i *int) float32

PathDataNext gets the next path data point, incrementing the index

func PathDataNextRel

func PathDataNextRel(data []PathData, i *int, cp math32.Vector2) math32.Vector2

PathDataNextRel gets the next 2 path data points as a relative vector and returns that relative vector added to current point

func PathDataNextVector added in v0.0.10

func PathDataNextVector(data []PathData, i *int) math32.Vector2

PathDataNextVector gets the next 2 path data points as a vector

func PathDataRender

func PathDataRender(data []PathData, pc *paint.Context)

PathDataRender traverses the path data and renders it using paint. We assume all the data has been validated and that n's are sufficient, etc

func PathDataStart

func PathDataStart(data []PathData) (vec math32.Vector2, ang float32)

PathDataStart gets the starting coords and angle from the path

func PathDataString

func PathDataString(data []PathData) string

PathDataString returns the string representation of the path data

func PathDataTransformAbs

func PathDataTransformAbs(data []PathData, i *int, xf math32.Matrix2, lpt math32.Vector2) math32.Vector2

PathDataTransformAbs does the transform of next two data points as absolute coords

func PathDataTransformRel

func PathDataTransformRel(data []PathData, i *int, xf math32.Matrix2, cp math32.Vector2) math32.Vector2

PathDataTransformRel does the transform of next two data points as relative coords compared to given cp coordinate. returns new *absolute* coordinate

func PathDataValidate

func PathDataValidate(data *[]PathData, errstr string) error

PathDataValidate validates the path data and emits error messages on log

func SVGNodeMarshalXML

func SVGNodeMarshalXML(itm tree.Node, enc *XMLEncoder, setName string) string

SVGNodeMarshalXML encodes just the given node under SVG to XML. returns name of node, for end tag -- if empty, then children will not be output.

func SVGNodeTreeMarshalXML

func SVGNodeTreeMarshalXML(itm Node, enc *XMLEncoder, setName string) (string, error)

SVGNodeTreeMarshalXML encodes item and any children to XML. returns any error, and name of element that enc.WriteEnd() should be called with -- allows for extra elements to be added at end of list.

func SVGNodeXMLGrad

func SVGNodeXMLGrad(nd *Gradient, name string, enc *XMLEncoder)

SVGNodeXMLGrad adds the XML for the given gradient to the given encoder. This is not in cogentcore.org/core/colors/gradient because it uses a lot of SVG and XML infrastructure defined here.

func SVGWalkPre

func SVGWalkPre(n Node, fun func(kni Node, knb *NodeBase) bool)

SVGWalkPre does tree.Node.WalkPre on given node using given walk function with SVG Node parameters. Automatically filters nil or deleted items. Return tree.Continue (true) to continue, and tree.Break (false) to terminate.

func SVGWalkPreNoDefs added in v0.0.5

func SVGWalkPreNoDefs(n Node, fun func(kni Node, knb *NodeBase) bool)

SVGWalkPreNoDefs does tree.Node.WalkPre on given node using given walk function with SVG Node parameters. Automatically filters nil or deleted items, and Defs nodes (IsDef) and MetaData, i.e., it only processes concrete graphical nodes. Return tree.Continue (true) to continue, and tree.Break (false) to terminate.

func SetFloat32SliceLen

func SetFloat32SliceLen(dat *[]float32, sz int)

SetFloat32SliceLen is a utility function to set given slice of float32 values to given length, reusing existing where possible and making a new one as needed. For use in WriteGeom routines.

func SetStdXMLAttr

func SetStdXMLAttr(ni Node, name, val string) bool

SetStdXMLAttr sets standard attributes of node given XML-style name / attribute values (e.g., from parsing XML / SVG files) -- returns true if handled

func SplitNameID added in v0.0.7

func SplitNameID(elnm, nm string) (bool, int)

SplitNameID splits name after the element name (e.g., 'rect') returning true if it starts with element name, and numerical id part after that element. if numerical id part is 0, then it didn't parse. SVG object names are element names + numerical id

func SplitNameIDDig added in v0.0.7

func SplitNameIDDig(nm string) (string, int)

SplitNameIDDig splits name into numerical end part and preceding name, based on string of digits from end of name. If Id == 0 then it was not specified or didn't parse. SVG object names are element names + numerical id

func XMLAddAttr

func XMLAddAttr(attr *[]xml.Attr, name, val string)

Types

type Circle

type Circle struct {
	NodeBase

	// position of the center of the circle
	Pos math32.Vector2 `xml:"{cx,cy}"`

	// radius of the circle
	Radius float32 `xml:"r"`
}

Circle is a SVG circle

func NewCircle

func NewCircle(parent tree.Node, name ...string) *Circle

NewCircle adds a new Circle with the given name to the given parent: Circle is a SVG circle

func (*Circle) ApplyDeltaTransform

func (g *Circle) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Circle) ApplyTransform

func (g *Circle) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Circle) LocalBBox

func (g *Circle) LocalBBox() math32.Box2

func (*Circle) New

func (t *Circle) New() tree.Node

New returns a new *Circle value

func (*Circle) NodeType added in v0.0.10

func (t *Circle) NodeType() *types.Type

NodeType returns the *types.Type of Circle

func (*Circle) OnInit

func (g *Circle) OnInit()

func (*Circle) ReadGeom

func (g *Circle) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Circle) Render

func (g *Circle) Render(sv *SVG)

func (*Circle) SVGName

func (g *Circle) SVGName() string

func (*Circle) SetClass

func (t *Circle) SetClass(v string) *Circle

SetClass sets the [Circle.Class]

func (*Circle) SetNodePos added in v0.0.7

func (g *Circle) SetNodePos(pos math32.Vector2)

func (*Circle) SetNodeSize added in v0.0.7

func (g *Circle) SetNodeSize(sz math32.Vector2)

func (*Circle) SetPos

func (t *Circle) SetPos(v math32.Vector2) *Circle

SetPos sets the [Circle.Pos]: position of the center of the circle

func (*Circle) SetRadius

func (t *Circle) SetRadius(v float32) *Circle

SetRadius sets the [Circle.Radius]: radius of the circle

func (*Circle) WriteGeom

func (g *Circle) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type ClipPath

type ClipPath struct {
	NodeBase
}

ClipPath is used for holding a path that renders as a clip path

func NewClipPath

func NewClipPath(parent tree.Node, name ...string) *ClipPath

NewClipPath adds a new ClipPath with the given name to the given parent: ClipPath is used for holding a path that renders as a clip path

func (*ClipPath) New

func (t *ClipPath) New() tree.Node

New returns a new *ClipPath value

func (*ClipPath) NodeType added in v0.0.10

func (t *ClipPath) NodeType() *types.Type

NodeType returns the *types.Type of ClipPath

func (*ClipPath) SVGName

func (g *ClipPath) SVGName() string

func (*ClipPath) SetClass

func (t *ClipPath) SetClass(v string) *ClipPath

SetClass sets the [ClipPath.Class]

type Ellipse

type Ellipse struct {
	NodeBase

	// position of the center of the ellipse
	Pos math32.Vector2 `xml:"{cx,cy}"`

	// radii of the ellipse in the horizontal, vertical axes
	Radii math32.Vector2 `xml:"{rx,ry}"`
}

Ellipse is a SVG ellipse

func NewEllipse

func NewEllipse(parent tree.Node, name ...string) *Ellipse

NewEllipse adds a new Ellipse with the given name to the given parent: Ellipse is a SVG ellipse

func (*Ellipse) ApplyDeltaTransform

func (g *Ellipse) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Ellipse) ApplyTransform

func (g *Ellipse) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Ellipse) LocalBBox

func (g *Ellipse) LocalBBox() math32.Box2

func (*Ellipse) New

func (t *Ellipse) New() tree.Node

New returns a new *Ellipse value

func (*Ellipse) NodeType added in v0.0.10

func (t *Ellipse) NodeType() *types.Type

NodeType returns the *types.Type of Ellipse

func (*Ellipse) OnInit

func (g *Ellipse) OnInit()

func (*Ellipse) ReadGeom

func (g *Ellipse) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Ellipse) Render

func (g *Ellipse) Render(sv *SVG)

func (*Ellipse) SVGName

func (g *Ellipse) SVGName() string

func (*Ellipse) SetClass

func (t *Ellipse) SetClass(v string) *Ellipse

SetClass sets the [Ellipse.Class]

func (*Ellipse) SetNodePos added in v0.0.7

func (g *Ellipse) SetNodePos(pos math32.Vector2)

func (*Ellipse) SetNodeSize added in v0.0.7

func (g *Ellipse) SetNodeSize(sz math32.Vector2)

func (*Ellipse) SetPos

func (t *Ellipse) SetPos(v math32.Vector2) *Ellipse

SetPos sets the [Ellipse.Pos]: position of the center of the ellipse

func (*Ellipse) SetRadii

func (t *Ellipse) SetRadii(v math32.Vector2) *Ellipse

SetRadii sets the [Ellipse.Radii]: radii of the ellipse in the horizontal, vertical axes

func (*Ellipse) WriteGeom

func (g *Ellipse) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Filter

type Filter struct {
	NodeBase
	FilterType string
}

Filter represents SVG filter* elements

func NewFilter

func NewFilter(parent tree.Node, name ...string) *Filter

NewFilter adds a new Filter with the given name to the given parent: Filter represents SVG filter* elements

func (*Filter) New

func (t *Filter) New() tree.Node

New returns a new *Filter value

func (*Filter) NodeType added in v0.0.10

func (t *Filter) NodeType() *types.Type

NodeType returns the *types.Type of Filter

func (*Filter) SVGName

func (g *Filter) SVGName() string

func (*Filter) SetClass

func (t *Filter) SetClass(v string) *Filter

SetClass sets the [Filter.Class]

func (*Filter) SetFilterType

func (t *Filter) SetFilterType(v string) *Filter

SetFilterType sets the [Filter.FilterType]

type Flow

type Flow struct {
	NodeBase
	FlowType string
}

Flow represents SVG flow* elements

func NewFlow

func NewFlow(parent tree.Node, name ...string) *Flow

NewFlow adds a new Flow with the given name to the given parent: Flow represents SVG flow* elements

func (*Flow) New

func (t *Flow) New() tree.Node

New returns a new *Flow value

func (*Flow) NodeType added in v0.0.10

func (t *Flow) NodeType() *types.Type

NodeType returns the *types.Type of Flow

func (*Flow) SVGName

func (g *Flow) SVGName() string

func (*Flow) SetClass

func (t *Flow) SetClass(v string) *Flow

SetClass sets the [Flow.Class]

func (*Flow) SetFlowType

func (t *Flow) SetFlowType(v string) *Flow

SetFlowType sets the [Flow.FlowType]

type Gradient

type Gradient struct {
	NodeBase

	// the color gradient
	Grad gradient.Gradient

	// name of another gradient to get stops from
	StopsName string
}

Gradient is used for holding a specified color gradient. The name is the id for lookup in url

func NewGradient

func NewGradient(parent tree.Node, name ...string) *Gradient

NewGradient adds a new Gradient with the given name to the given parent: Gradient is used for holding a specified color gradient. The name is the id for lookup in url

func (*Gradient) GradientTypeName

func (gr *Gradient) GradientTypeName() string

GradientTypeName returns the SVG-style type name of gradient: linearGradient or radialGradient

func (*Gradient) New

func (t *Gradient) New() tree.Node

New returns a new *Gradient value

func (*Gradient) NodeType added in v0.0.10

func (t *Gradient) NodeType() *types.Type

NodeType returns the *types.Type of Gradient

func (*Gradient) SetClass

func (t *Gradient) SetClass(v string) *Gradient

SetClass sets the [Gradient.Class]

func (*Gradient) SetGrad

func (t *Gradient) SetGrad(v gradient.Gradient) *Gradient

SetGrad sets the [Gradient.Grad]: the color gradient

func (*Gradient) SetStopsName

func (t *Gradient) SetStopsName(v string) *Gradient

SetStopsName sets the [Gradient.StopsName]: name of another gradient to get stops from

type Group

type Group struct {
	NodeBase
}

Group groups together SVG elements. Provides a common transform for all group elements and shared style properties.

func NewGroup

func NewGroup(parent tree.Node, name ...string) *Group

NewGroup adds a new Group with the given name to the given parent: Group groups together SVG elements. Provides a common transform for all group elements and shared style properties.

func (*Group) ApplyDeltaTransform

func (g *Group) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Group) ApplyTransform

func (g *Group) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Group) EnforceSVGName

func (g *Group) EnforceSVGName() bool

func (*Group) New

func (t *Group) New() tree.Node

New returns a new *Group value

func (*Group) NodeBBox

func (g *Group) NodeBBox(sv *SVG) image.Rectangle

func (*Group) NodeType added in v0.0.10

func (t *Group) NodeType() *types.Type

NodeType returns the *types.Type of Group

func (*Group) ReadGeom

func (g *Group) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Group) Render

func (g *Group) Render(sv *SVG)

func (*Group) SVGName

func (g *Group) SVGName() string

func (*Group) SetClass

func (t *Group) SetClass(v string) *Group

SetClass sets the [Group.Class]

func (*Group) WriteGeom

func (g *Group) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Image

type Image struct {
	NodeBase

	// position of the top-left of the image
	Pos math32.Vector2 `xml:"{x,y}"`

	// rendered size of the image (imposes a scaling on image when it is rendered)
	Size math32.Vector2 `xml:"{width,height}"`

	// file name of image loaded -- set by OpenImage
	Filename string

	// how to scale and align the image
	ViewBox ViewBox `xml:"viewbox"`

	// the image pixels
	Pixels *image.RGBA `xml:"-" json:"-" view:"-"`
}

Image is an SVG image (bitmap)

func NewImage

func NewImage(parent tree.Node, name ...string) *Image

NewImage adds a new Image with the given name to the given parent: Image is an SVG image (bitmap)

func (*Image) ApplyDeltaTransform

func (g *Image) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Image) ApplyTransform

func (g *Image) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Image) DrawImage

func (g *Image) DrawImage(sv *SVG)

func (*Image) LocalBBox

func (g *Image) LocalBBox() math32.Box2

func (*Image) New

func (t *Image) New() tree.Node

New returns a new *Image value

func (*Image) NodeBBox

func (g *Image) NodeBBox(sv *SVG) image.Rectangle

func (*Image) NodeType added in v0.0.10

func (t *Image) NodeType() *types.Type

NodeType returns the *types.Type of Image

func (*Image) OpenImage

func (g *Image) OpenImage(filename string, width, height float32) error

OpenImage opens an image for the bitmap, and resizes to the size of the image or the specified size -- pass 0 for width and/or height to use the actual image size for that dimension

func (*Image) ReadGeom

func (g *Image) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Image) Render

func (g *Image) Render(sv *SVG)

func (*Image) SVGName

func (g *Image) SVGName() string

func (*Image) SaveImage

func (g *Image) SaveImage(filename string) error

SaveImage saves current image to a file

func (*Image) SetClass

func (t *Image) SetClass(v string) *Image

SetClass sets the [Image.Class]

func (*Image) SetFilename

func (t *Image) SetFilename(v string) *Image

SetFilename sets the [Image.Filename]: file name of image loaded -- set by OpenImage

func (*Image) SetImage

func (g *Image) SetImage(img image.Image, width, height float32)

SetImage sets an image for the bitmap, and resizes to the size of the image or the specified size -- pass 0 for width and/or height to use the actual image size for that dimension. Copies from given image into internal image for this bitmap.

func (*Image) SetImageSize

func (g *Image) SetImageSize(nwsz image.Point)

SetImageSize sets size of the bitmap image. This does not resize any existing image, just makes a new image if the size is different

func (*Image) SetNodePos added in v0.0.7

func (g *Image) SetNodePos(pos math32.Vector2)

func (*Image) SetNodeSize added in v0.0.7

func (g *Image) SetNodeSize(sz math32.Vector2)

func (*Image) SetPixels

func (t *Image) SetPixels(v *image.RGBA) *Image

SetPixels sets the [Image.Pixels]: the image pixels

func (*Image) SetPos

func (t *Image) SetPos(v math32.Vector2) *Image

SetPos sets the [Image.Pos]: position of the top-left of the image

func (*Image) SetSize

func (t *Image) SetSize(v math32.Vector2) *Image

SetSize sets the [Image.Size]: rendered size of the image (imposes a scaling on image when it is rendered)

func (*Image) SetViewBox added in v0.0.3

func (t *Image) SetViewBox(v ViewBox) *Image

SetViewBox sets the [Image.ViewBox]: how to scale and align the image

func (*Image) WriteGeom

func (g *Image) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Line

type Line struct {
	NodeBase

	// position of the start of the line
	Start math32.Vector2 `xml:"{x1,y1}"`

	// position of the end of the line
	End math32.Vector2 `xml:"{x2,y2}"`
}

Line is a SVG line

func NewLine

func NewLine(parent tree.Node, name ...string) *Line

NewLine adds a new Line with the given name to the given parent: Line is a SVG line

func (*Line) ApplyDeltaTransform

func (g *Line) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Line) ApplyTransform

func (g *Line) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Line) LocalBBox

func (g *Line) LocalBBox() math32.Box2

func (*Line) New

func (t *Line) New() tree.Node

New returns a new *Line value

func (*Line) NodeType added in v0.0.10

func (t *Line) NodeType() *types.Type

NodeType returns the *types.Type of Line

func (*Line) OnInit

func (g *Line) OnInit()

func (*Line) ReadGeom

func (g *Line) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Line) Render

func (g *Line) Render(sv *SVG)

func (*Line) SVGName

func (g *Line) SVGName() string

func (*Line) SetClass

func (t *Line) SetClass(v string) *Line

SetClass sets the [Line.Class]

func (*Line) SetEnd

func (t *Line) SetEnd(v math32.Vector2) *Line

SetEnd sets the [Line.End]: position of the end of the line

func (*Line) SetPos

func (g *Line) SetPos(pos math32.Vector2)

func (*Line) SetSize

func (g *Line) SetSize(sz math32.Vector2)

func (*Line) SetStart

func (t *Line) SetStart(v math32.Vector2) *Line

SetStart sets the [Line.Start]: position of the start of the line

func (*Line) WriteGeom

func (g *Line) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Marker

type Marker struct {
	NodeBase

	// reference position to align the vertex position with, specified in ViewBox coordinates
	RefPos math32.Vector2 `xml:"{refX,refY}"`

	// size of marker to render, in Units units
	Size math32.Vector2 `xml:"{markerWidth,markerHeight}"`

	// units to use
	Units MarkerUnits `xml:"markerUnits"`

	// viewbox defines the internal coordinate system for the drawing elements within the marker
	ViewBox ViewBox

	// orientation of the marker -- either 'auto' or an angle
	Orient string `xml:"orient"`

	// current vertex position
	VertexPos math32.Vector2

	// current vertex angle in radians
	VertexAngle float32

	// current stroke width
	StrokeWidth float32

	// net transform computed from settings and current values -- applied prior to rendering
	Transform math32.Matrix2

	// effective size for actual rendering
	EffSize math32.Vector2
}

Marker represents marker elements that can be drawn along paths (arrow heads, etc)

func NewMarker

func NewMarker(parent tree.Node, name ...string) *Marker

NewMarker adds a new Marker with the given name to the given parent: Marker represents marker elements that can be drawn along paths (arrow heads, etc)

func (*Marker) BBoxes

func (g *Marker) BBoxes(sv *SVG)

func (*Marker) EnforceSVGName

func (g *Marker) EnforceSVGName() bool

func (*Marker) New

func (t *Marker) New() tree.Node

New returns a new *Marker value

func (*Marker) NodeType added in v0.0.10

func (t *Marker) NodeType() *types.Type

NodeType returns the *types.Type of Marker

func (*Marker) Render

func (g *Marker) Render(sv *SVG)

func (*Marker) RenderMarker

func (mrk *Marker) RenderMarker(sv *SVG, vertexPos math32.Vector2, vertexAng, strokeWidth float32)

RenderMarker renders the marker using given vertex position, angle (in radians), and stroke width

func (*Marker) SVGName

func (g *Marker) SVGName() string

func (*Marker) SetClass

func (t *Marker) SetClass(v string) *Marker

SetClass sets the [Marker.Class]

func (*Marker) SetEffSize

func (t *Marker) SetEffSize(v math32.Vector2) *Marker

SetEffSize sets the [Marker.EffSize]: effective size for actual rendering

func (*Marker) SetOrient

func (t *Marker) SetOrient(v string) *Marker

SetOrient sets the [Marker.Orient]: orientation of the marker -- either 'auto' or an angle

func (*Marker) SetRefPos

func (t *Marker) SetRefPos(v math32.Vector2) *Marker

SetRefPos sets the [Marker.RefPos]: reference position to align the vertex position with, specified in ViewBox coordinates

func (*Marker) SetSize

func (t *Marker) SetSize(v math32.Vector2) *Marker

SetSize sets the [Marker.Size]: size of marker to render, in Units units

func (*Marker) SetStrokeWidth

func (t *Marker) SetStrokeWidth(v float32) *Marker

SetStrokeWidth sets the [Marker.StrokeWidth]: current stroke width

func (*Marker) SetTransform

func (t *Marker) SetTransform(v math32.Matrix2) *Marker

SetTransform sets the [Marker.Transform]: net transform computed from settings and current values -- applied prior to rendering

func (*Marker) SetUnits

func (t *Marker) SetUnits(v MarkerUnits) *Marker

SetUnits sets the [Marker.Units]: units to use

func (*Marker) SetVertexAngle

func (t *Marker) SetVertexAngle(v float32) *Marker

SetVertexAngle sets the [Marker.VertexAngle]: current vertex angle in radians

func (*Marker) SetVertexPos

func (t *Marker) SetVertexPos(v math32.Vector2) *Marker

SetVertexPos sets the [Marker.VertexPos]: current vertex position

func (*Marker) SetViewBox

func (t *Marker) SetViewBox(v ViewBox) *Marker

SetViewBox sets the [Marker.ViewBox]: viewbox defines the internal coordinate system for the drawing elements within the marker

type MarkerUnits

type MarkerUnits int32 //enum: enum

MarkerUnits specifies units to use for svg marker elements

const (
	StrokeWidth MarkerUnits = iota
	UserSpaceOnUse
	MarkerUnitsN
)

type MetaData

type MetaData struct {
	NodeBase
	MetaData string
}

MetaData is used for holding meta data info

func NewMetaData

func NewMetaData(parent tree.Node, name ...string) *MetaData

NewMetaData adds a new MetaData with the given name to the given parent: MetaData is used for holding meta data info

func (*MetaData) New

func (t *MetaData) New() tree.Node

New returns a new *MetaData value

func (*MetaData) NodeType added in v0.0.10

func (t *MetaData) NodeType() *types.Type

NodeType returns the *types.Type of MetaData

func (*MetaData) SetClass

func (t *MetaData) SetClass(v string) *MetaData

SetClass sets the [MetaData.Class]

func (*MetaData) SetMetaData

func (t *MetaData) SetMetaData(v string) *MetaData

SetMetaData sets the [MetaData.MetaData]

type Node

type Node interface {
	tree.Node

	// AsNodeBase returns a generic svg.NodeBase for our node -- gives generic
	// access to all the base-level data structures without requiring
	// interface methods.
	AsNodeBase() *NodeBase

	// PaintStyle returns the SVG Paint style object for this node
	PaintStyle() *styles.Paint

	// Style updates the Paint style for this node
	Style(sv *SVG)

	// Render draws the node to the svg image
	Render(sv *SVG)

	// BBoxes computes BBox and VisBBox during Render
	BBoxes(sv *SVG)

	// LocalBBox returns the bounding box of node in local dimensions
	LocalBBox() math32.Box2

	// NodeBBox returns the bounding box in image coordinates for this node
	NodeBBox(sv *SVG) image.Rectangle

	// SetNodePos sets the upper left effective position of this element, in local dimensions
	SetNodePos(pos math32.Vector2)

	// SetNodeSize sets the overall effective size of this element, in local dimensions
	SetNodeSize(sz math32.Vector2)

	// ApplyTransform applies the given 2D transform to the geometry of this node
	// this just does a direct transform multiplication on coordinates.
	ApplyTransform(sv *SVG, xf math32.Matrix2)

	// ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node
	// relative to given point.  Trans translation and point are in top-level coordinates,
	// so must be transformed into local coords first.
	// Point is upper left corner of selection box that anchors the translation and scaling,
	// and for rotation it is the center point around which to rotate
	ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

	// WriteGeom writes the geometry of the node to a slice of floating point numbers
	// the length and ordering of which is specific to each node type.
	// Slice must be passed and will be resized if not the correct length.
	WriteGeom(sv *SVG, dat *[]float32)

	// ReadGeom reads the geometry of the node from a slice of floating point numbers
	// the length and ordering of which is specific to each node type.
	ReadGeom(sv *SVG, dat []float32)

	// SVGName returns the SVG element name (e.g., "rect", "path" etc)
	SVGName() string

	// EnforceSVGName returns true if in general this element should
	// be named with its SVGName plus a unique id.
	// Groups and Markers are false.
	EnforceSVGName() bool
}

Node is the interface for all SVG nodes

func FirstNonGroupNode

func FirstNonGroupNode(n Node) Node

FirstNonGroupNode returns the first item that is not a group recursing into groups until a non-group item is found.

func NodesContainingPoint

func NodesContainingPoint(n Node, pt image.Point, leavesOnly bool) []Node

NodesContainingPoint returns all Nodes with Bounding Box that contains given point, optionally only those that are terminal nodes (no leaves). Excludes the starting node.

type NodeBase

type NodeBase struct {
	tree.NodeBase

	// user-defined class name(s) used primarily for attaching
	// CSS styles to different display elements.
	// Multiple class names can be used to combine properties:
	// use spaces to separate per css standard.
	Class string

	// CSS is the cascading style sheet at this level.
	// These styles apply here and to everything below, until superceded.
	// Use .class and #name Properties elements to apply entire styles
	// to given elements, and type for element type.
	CSS map[string]any `xml:"css" set:"-"`

	// CSSAgg is the aggregated css properties from all higher nodes down to this node.
	CSSAgg map[string]any `copier:"-" json:"-" xml:"-" set:"-" view:"no-inline"`

	// bounding box for the node within the SVG Pixels image.
	// This one can be outside the visible range of the SVG image.
	// VisBBox is intersected and only shows visible portion.
	BBox image.Rectangle `copier:"-" json:"-" xml:"-" set:"-"`

	// visible bounding box for the node intersected with the SVG image geometry
	VisBBox image.Rectangle `copier:"-" json:"-" xml:"-" set:"-"`

	// paint style information for this node
	Paint styles.Paint `json:"-" xml:"-" set:"-"`
}

svg.NodeBase is the base type for elements within the SVG scenegraph

func NewNodeBase

func NewNodeBase(parent tree.Node, name ...string) *NodeBase

NewNodeBase adds a new NodeBase with the given name to the given parent: svg.NodeBase is the base type for elements within the SVG scenegraph

func (*NodeBase) ApplyCSS

func (g *NodeBase) ApplyCSS(sv *SVG, key string, css map[string]any) bool

ApplyCSS applies css styles to given node, using key to select sub-properties from overall properties list

func (*NodeBase) ApplyDeltaTransform

func (g *NodeBase) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*NodeBase) ApplyTransform

func (g *NodeBase) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node this just does a direct transform multiplication on coordinates.

func (*NodeBase) AsNodeBase

func (g *NodeBase) AsNodeBase() *NodeBase

func (*NodeBase) BBoxes

func (g *NodeBase) BBoxes(sv *SVG)

ComputeBBox is called by default in render to compute bounding boxes for gui interaction -- can only be done in rendering because that is when all the proper transforms are all in place -- VpBBox is intersected with parent SVG

func (*NodeBase) BaseIface

func (n *NodeBase) BaseIface() reflect.Type

func (*NodeBase) DeltaTransform

func (g *NodeBase) DeltaTransform(trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2, self bool) (math32.Matrix2, math32.Vector2)

DeltaTransform computes the net transform matrix for given delta transform parameters and the transformed version of the reference point. If self is true, then include the current node self transform, otherwise don't. Groups do not but regular rendering nodes do.

func (*NodeBase) EnforceSVGName

func (g *NodeBase) EnforceSVGName() bool

func (*NodeBase) GradientApplyTransform

func (g *NodeBase) GradientApplyTransform(sv *SVG, xf math32.Matrix2)

GradientApplyTransform applies the given transform to any gradients for this node, that are using specific coordinates (not bounding box which is automatic)

func (*NodeBase) GradientApplyTransformPt

func (g *NodeBase) GradientApplyTransformPt(sv *SVG, xf math32.Matrix2, pt math32.Vector2)

GradientApplyTransformPt applies the given transform with ctr point to any gradients for this node, that are using specific coordinates (not bounding box which is automatic)

func (*NodeBase) GradientReadPts

func (g *NodeBase) GradientReadPts(sv *SVG, dat []float32)

GradientReadPts reads the geometry of the gradients for this node from a slice of floating point numbers, reading from the end.

func (*NodeBase) GradientWritePts

func (g *NodeBase) GradientWritePts(sv *SVG, dat *[]float32)

GradientWritePts writes the geometry of the gradients for this node to a slice of floating point numbers, appending to end of slice.

func (*NodeBase) IsDefs

func (g *NodeBase) IsDefs() bool

IsDefs returns true if is in the Defs of parent SVG

func (*NodeBase) LocalBBox

func (g *NodeBase) LocalBBox() math32.Box2

func (*NodeBase) LocalBBoxToWin

func (g *NodeBase) LocalBBoxToWin(bb math32.Box2) image.Rectangle

LocalBBoxToWin converts a local bounding box to SVG coordinates

func (*NodeBase) LocalLineWidth

func (g *NodeBase) LocalLineWidth() float32

LocalLineWidth returns the line width in local coordinates

func (*NodeBase) New

func (t *NodeBase) New() tree.Node

New returns a new *NodeBase value

func (*NodeBase) NodeBBox

func (g *NodeBase) NodeBBox(sv *SVG) image.Rectangle

func (*NodeBase) NodeType added in v0.0.10

func (t *NodeBase) NodeType() *types.Type

NodeType returns the *types.Type of NodeBase

func (*NodeBase) PaintStyle

func (g *NodeBase) PaintStyle() *styles.Paint

func (*NodeBase) ParTransform

func (g *NodeBase) ParTransform(self bool) math32.Matrix2

ParTransform returns the full compounded 2D transform matrix for all of the parents of this node. If self is true, then include our own transform too.

func (*NodeBase) PushTransform

func (g *NodeBase) PushTransform(sv *SVG) (bool, *paint.Context)

PushTransform checks our bounding box and visibility, returning false if out of bounds. If visible, pushes our transform. Must be called as first step in Render.

func (*NodeBase) ReadGeom

func (g *NodeBase) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*NodeBase) ReadTransform

func (g *NodeBase) ReadTransform(dat []float32, idx int)

ReadTransform reads the node transform from slice at starting index.

func (*NodeBase) Render

func (g *NodeBase) Render(sv *SVG)

func (*NodeBase) RenderChildren

func (g *NodeBase) RenderChildren(sv *SVG)

func (*NodeBase) SVGName

func (g *NodeBase) SVGName() string

func (*NodeBase) SetClass

func (t *NodeBase) SetClass(v string) *NodeBase

SetClass sets the [NodeBase.Class]: user-defined class name(s) used primarily for attaching CSS styles to different display elements. Multiple class names can be used to combine properties: use spaces to separate per css standard.

func (*NodeBase) SetColorProperties added in v0.0.10

func (g *NodeBase) SetColorProperties(prop, color string)

SetColorProperties sets color property from a string representation. It breaks color alpha out as opacity. prop is either "stroke" or "fill"

func (*NodeBase) SetNodePos added in v0.0.7

func (g *NodeBase) SetNodePos(pos math32.Vector2)

func (*NodeBase) SetNodeSize added in v0.0.7

func (g *NodeBase) SetNodeSize(sz math32.Vector2)

func (*NodeBase) SetPos

func (g *NodeBase) SetPos(pos math32.Vector2)

func (*NodeBase) SetSize

func (g *NodeBase) SetSize(sz math32.Vector2)

func (*NodeBase) Style

func (g *NodeBase) Style(sv *SVG)

Style styles the Paint values directly from node properties

func (*NodeBase) StyleCSS

func (g *NodeBase) StyleCSS(sv *SVG, css map[string]any)

StyleCSS applies css style properties to given SVG node parsing out type, .class, and #name selectors

func (*NodeBase) WriteGeom

func (g *NodeBase) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

func (*NodeBase) WriteTransform

func (g *NodeBase) WriteTransform(dat []float32, idx int)

WriteTransform writes the node transform to slice at starting index. slice must already be allocated sufficiently.

type NodeFlags

type NodeFlags tree.Flags //enums:bitflag

NodeFlags extend tree.Flags to hold SVG node state.

const (
	IsDef NodeFlags = NodeFlags(tree.FlagsN) + iota
)
const NodeFlagsN NodeFlags = 2

NodeFlagsN is the highest valid value for type NodeFlags, plus one.

func NodeFlagsValues

func NodeFlagsValues() []NodeFlags

NodeFlagsValues returns all possible values for the type NodeFlags.

func (NodeFlags) BitIndexString

func (i NodeFlags) BitIndexString() string

BitIndexString returns the string representation of this NodeFlags value if it is a bit index value (typically an enum constant), and not an actual bit flag value.

func (NodeFlags) Desc

func (i NodeFlags) Desc() string

Desc returns the description of the NodeFlags value.

func (NodeFlags) HasFlag

func (i NodeFlags) HasFlag(f enums.BitFlag) bool

HasFlag returns whether these bit flags have the given bit flag set.

func (NodeFlags) Int64

func (i NodeFlags) Int64() int64

Int64 returns the NodeFlags value as an int64.

func (NodeFlags) MarshalText

func (i NodeFlags) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*NodeFlags) SetFlag

func (i *NodeFlags) SetFlag(on bool, f ...enums.BitFlag)

SetFlag sets the value of the given flags in these flags to the given value.

func (*NodeFlags) SetInt64

func (i *NodeFlags) SetInt64(in int64)

SetInt64 sets the NodeFlags value from an int64.

func (*NodeFlags) SetString

func (i *NodeFlags) SetString(s string) error

SetString sets the NodeFlags value from its string representation, and returns an error if the string is invalid.

func (*NodeFlags) SetStringOr

func (i *NodeFlags) SetStringOr(s string) error

SetStringOr sets the NodeFlags value from its string representation while preserving any bit flags already set, and returns an error if the string is invalid.

func (NodeFlags) String

func (i NodeFlags) String() string

String returns the string representation of this NodeFlags value.

func (*NodeFlags) UnmarshalText

func (i *NodeFlags) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (NodeFlags) Values

func (i NodeFlags) Values() []enums.Enum

Values returns all possible values for the type NodeFlags.

type Path

type Path struct {
	NodeBase

	// the path data to render -- path commands and numbers are serialized, with each command specifying the number of floating-point coord data points that follow
	Data []PathData `xml:"-" set:"-"`

	// string version of the path data
	DataStr string `xml:"d"`
}

Path renders SVG data sequences that can render just about anything

func NewPath

func NewPath(parent tree.Node, name ...string) *Path

NewPath adds a new Path with the given name to the given parent: Path renders SVG data sequences that can render just about anything

func (*Path) ApplyDeltaTransform

func (g *Path) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Path) ApplyTransform

func (g *Path) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Path) ApplyTransformImpl

func (g *Path) ApplyTransformImpl(xf math32.Matrix2, lpt math32.Vector2)

ApplyTransformImpl does the implementation of applying a transform to all points

func (*Path) LocalBBox

func (g *Path) LocalBBox() math32.Box2

func (*Path) New

func (t *Path) New() tree.Node

New returns a new *Path value

func (*Path) NodeType added in v0.0.10

func (t *Path) NodeType() *types.Type

NodeType returns the *types.Type of Path

func (*Path) ReadGeom

func (g *Path) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Path) Render

func (g *Path) Render(sv *SVG)

func (*Path) SVGName

func (g *Path) SVGName() string

func (*Path) SetClass

func (t *Path) SetClass(v string) *Path

SetClass sets the [Path.Class]

func (*Path) SetData

func (g *Path) SetData(data string) error

SetData sets the path data to given string, parsing it into an optimized form used for rendering

func (*Path) SetDataStr

func (t *Path) SetDataStr(v string) *Path

SetDataStr sets the [Path.DataStr]: string version of the path data

func (*Path) SetPos

func (g *Path) SetPos(pos math32.Vector2)

func (*Path) SetSize

func (g *Path) SetSize(sz math32.Vector2)

func (*Path) WriteGeom

func (g *Path) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type PathCmds

type PathCmds byte //enum: enum

PathCmds are the commands within the path SVG drawing data type

const (
	// move pen, abs coords
	PcM PathCmds = iota
	// move pen, rel coords
	Pcm
	// lineto, abs
	PcL
	// lineto, rel
	Pcl
	// horizontal lineto, abs
	PcH
	// relative lineto, rel
	Pch
	// vertical lineto, abs
	PcV
	// vertical lineto, rel
	Pcv
	// Bezier curveto, abs
	PcC
	// Bezier curveto, rel
	Pcc
	// smooth Bezier curveto, abs
	PcS
	// smooth Bezier curveto, rel
	Pcs
	// quadratic Bezier curveto, abs
	PcQ
	// quadratic Bezier curveto, rel
	Pcq
	// smooth quadratic Bezier curveto, abs
	PcT
	// smooth quadratic Bezier curveto, rel
	Pct
	// elliptical arc, abs
	PcA
	// elliptical arc, rel
	Pca
	// close path
	PcZ
	// close path
	Pcz
	// error -- invalid command
	PcErr
)

func PathDataNextCmd

func PathDataNextCmd(data []PathData, i *int) (PathCmds, int)

PathDataNextCmd gets the next path data command, incrementing the index -- ++ not an expression so its clunky

func PathDecodeCmd

func PathDecodeCmd(r rune) PathCmds

PathDecodeCmd decodes rune into corresponding command

func (PathCmds) EncCmd

func (pc PathCmds) EncCmd(n int) PathData

EncCmd encodes command and n into PathData

type PathData

type PathData float32

PathData encodes the svg path data, using 32-bit floats which are converted into uint32 for path commands, and contain the command as the first 5 bits, and the remaining 27 bits are the number of data points following the path command to interpret as numbers.

func PathDataParse

func PathDataParse(d string) ([]PathData, error)

PathDataParse parses a string representation of the path data into compiled path data

func (PathData) Cmd

func (pd PathData) Cmd() (PathCmds, int)

Cmd decodes path data as a command and a number of subsequent values for that command

type Polygon

type Polygon struct {
	Polyline
}

Polygon is a SVG polygon

func NewPolygon

func NewPolygon(parent tree.Node, name ...string) *Polygon

NewPolygon adds a new Polygon with the given name to the given parent: Polygon is a SVG polygon

func (*Polygon) New

func (t *Polygon) New() tree.Node

New returns a new *Polygon value

func (*Polygon) NodeType added in v0.0.10

func (t *Polygon) NodeType() *types.Type

NodeType returns the *types.Type of Polygon

func (*Polygon) Render

func (g *Polygon) Render(sv *SVG)

func (*Polygon) SVGName

func (g *Polygon) SVGName() string

func (*Polygon) SetClass

func (t *Polygon) SetClass(v string) *Polygon

SetClass sets the [Polygon.Class]

func (*Polygon) SetPoints

func (t *Polygon) SetPoints(v ...math32.Vector2) *Polygon

SetPoints sets the [Polygon.Points]

type Polyline

type Polyline struct {
	NodeBase

	// the coordinates to draw -- does a moveto on the first, then lineto for all the rest
	Points []math32.Vector2 `xml:"points"`
}

Polyline is a SVG multi-line shape

func NewPolyline

func NewPolyline(parent tree.Node, name ...string) *Polyline

NewPolyline adds a new Polyline with the given name to the given parent: Polyline is a SVG multi-line shape

func (*Polyline) ApplyDeltaTransform

func (g *Polyline) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Polyline) ApplyTransform

func (g *Polyline) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Polyline) LocalBBox

func (g *Polyline) LocalBBox() math32.Box2

func (*Polyline) New

func (t *Polyline) New() tree.Node

New returns a new *Polyline value

func (*Polyline) NodeType added in v0.0.10

func (t *Polyline) NodeType() *types.Type

NodeType returns the *types.Type of Polyline

func (*Polyline) ReadGeom

func (g *Polyline) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Polyline) Render

func (g *Polyline) Render(sv *SVG)

func (*Polyline) SVGName

func (g *Polyline) SVGName() string

func (*Polyline) SetClass

func (t *Polyline) SetClass(v string) *Polyline

SetClass sets the [Polyline.Class]

func (*Polyline) SetPoints

func (t *Polyline) SetPoints(v ...math32.Vector2) *Polyline

SetPoints sets the [Polyline.Points]: the coordinates to draw -- does a moveto on the first, then lineto for all the rest

func (*Polyline) SetPos

func (g *Polyline) SetPos(pos math32.Vector2)

func (*Polyline) SetSize

func (g *Polyline) SetSize(sz math32.Vector2)

func (*Polyline) WriteGeom

func (g *Polyline) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type Rect

type Rect struct {
	NodeBase

	// position of the top-left of the rectangle
	Pos math32.Vector2 `xml:"{x,y}"`

	// size of the rectangle
	Size math32.Vector2 `xml:"{width,height}"`

	// radii for curved corners, as a proportion of width, height
	Radius math32.Vector2 `xml:"{rx,ry}"`
}

Rect is a SVG rectangle, optionally with rounded corners

func NewRect

func NewRect(parent tree.Node, name ...string) *Rect

NewRect adds a new Rect with the given name to the given parent: Rect is a SVG rectangle, optionally with rounded corners

func (*Rect) ApplyDeltaTransform

func (g *Rect) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Rect) ApplyTransform

func (g *Rect) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Rect) LocalBBox

func (g *Rect) LocalBBox() math32.Box2

func (*Rect) New

func (t *Rect) New() tree.Node

New returns a new *Rect value

func (*Rect) NodeType added in v0.0.10

func (t *Rect) NodeType() *types.Type

NodeType returns the *types.Type of Rect

func (*Rect) OnInit

func (g *Rect) OnInit()

func (*Rect) ReadGeom

func (g *Rect) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Rect) Render

func (g *Rect) Render(sv *SVG)

func (*Rect) SVGName

func (g *Rect) SVGName() string

func (*Rect) SetClass

func (t *Rect) SetClass(v string) *Rect

SetClass sets the [Rect.Class]

func (*Rect) SetNodePos added in v0.0.7

func (g *Rect) SetNodePos(pos math32.Vector2)

func (*Rect) SetNodeSize added in v0.0.7

func (g *Rect) SetNodeSize(sz math32.Vector2)

func (*Rect) SetPos

func (t *Rect) SetPos(v math32.Vector2) *Rect

SetPos sets the [Rect.Pos]: position of the top-left of the rectangle

func (*Rect) SetRadius

func (t *Rect) SetRadius(v math32.Vector2) *Rect

SetRadius sets the [Rect.Radius]: radii for curved corners, as a proportion of width, height

func (*Rect) SetSize

func (t *Rect) SetSize(v math32.Vector2) *Rect

SetSize sets the [Rect.Size]: size of the rectangle

func (*Rect) WriteGeom

func (g *Rect) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type SVG

type SVG struct {
	// Name is the name of the SVG -- e.g., the filename if loaded
	Name string

	// the title of the svg
	Title string `xml:"title"`

	// the description of the svg
	Desc string `xml:"desc"`

	// Background is the image/color to fill the background with,
	// if any.
	Background image.Image

	// Color can be set to provide a default Fill and Stroke Color value
	Color image.Image

	// Size is size of image, Pos is offset within any parent viewport.
	// Node bounding boxes are based on 0 Pos offset within Pixels image
	Geom math32.Geom2DInt

	// physical width of the drawing, e.g., when printed.
	// Does not affect rendering, metadata.
	PhysWidth units.Value

	// physical height of the drawing, e.g., when printed.
	// Does not affect rendering, metadata.
	PhysHeight units.Value

	// InvertY, when applying the ViewBox transform, also flip the Y axis so that
	// the smallest Y value is at the bottom of the SVG box,
	// instead of being at the top as it is by default.
	InvertY bool

	// Translate specifies a translation to apply beyond what is specified in the SVG,
	// and its ViewBox transform.
	Translate math32.Vector2

	// Scale specifies a zoom scale factor to apply beyond what is specified in the SVG,
	// and its ViewBox transform.
	Scale float32

	// render state for rendering
	RenderState paint.State `copier:"-" json:"-" xml:"-" edit:"-"`

	// live pixels that we render into
	Pixels *image.RGBA `copier:"-" json:"-" xml:"-" edit:"-"`

	// all defs defined elements go here (gradients, symbols, etc)
	Defs Group

	// root of the svg tree.  top-level viewbox and paint style here
	Root SVGNode

	// map of def names to index. uses starting index to find element.
	// always updated after each search.
	DefIndexes map[string]int `view:"-" json:"-" xml:"-"`

	// map of unique numeric ids for all elements.
	// Used for allocating new unique id numbers, appended to end of elements.
	// See NewUniqueID, GatherIDs
	UniqueIds map[int]struct{} `view:"-" json:"-" xml:"-"`

	// flag is set when the SVG is rendering
	IsRendering bool

	// mutex for protecting rendering
	RenderMu sync.Mutex `view:"-" json:"-" xml:"-"`
}

SVG is an SVG object.

func NewSVG

func NewSVG(width, height int) *SVG

NewSVG creates a SVG with Pixels Image of the specified width and height

func (*SVG) Base

func (sv *SVG) Base() color.RGBA

Base returns the current Color activated in the context. Color has support for special color names that are relative to this current color.

func (*SVG) Config

func (sv *SVG) Config(width, height int)

Config configures the SVG, setting image to given size and initializing all relevant fields.

func (*SVG) DeleteAll

func (sv *SVG) DeleteAll()

DeleteAll deletes any existing elements in this svg

func (*SVG) FillViewport

func (sv *SVG) FillViewport()

func (*SVG) FindDefByName

func (sv *SVG) FindDefByName(defnm string) Node

FindDefByName finds Defs item by name, using cached indexes for speed

func (*SVG) FindNamedElement

func (sv *SVG) FindNamedElement(name string) Node

func (*SVG) GatherIDs added in v0.0.7

func (sv *SVG) GatherIDs()

GatherIDs gathers all the numeric id suffixes currently in use. It automatically renames any that are not unique or empty.

func (*SVG) GradientByName

func (sv *SVG) GradientByName(n Node, grnm string) *Gradient

GradientByName returns the gradient of given name, stored on SVG node

func (*SVG) GradientCloneNodeProp

func (sv *SVG) GradientCloneNodeProp(n Node, prop string) *Gradient

GradientCloneNodeProp creates a new clone of the existing gradient for node if set for given property key ("fill" or "stroke"). returns new gradient.

func (*SVG) GradientDeleteForNode

func (sv *SVG) GradientDeleteForNode(n Node, grnm string) bool

GradientDeleteForNode deletes the node-specific gradient on given node of given name, which can be a full url(# name or just the bare name. Returns true if deleted.

func (*SVG) GradientDeleteNodeProp

func (sv *SVG) GradientDeleteNodeProp(n Node, prop string) bool

GradientDeleteNodeProp deletes any existing gradient for node if set for given property key ("fill" or "stroke"). Returns true if deleted.

func (*SVG) GradientNew

func (sv *SVG) GradientNew(radial bool) (*Gradient, string)

GradientNew adds a new gradient, either linear or radial, with a new unique id

func (*SVG) GradientNewForNode

func (sv *SVG) GradientNewForNode(n Node, radial bool, stops string) (*Gradient, string)

GradientNewForNode adds a new gradient specific to given node that points to given stops name. returns the new gradient and the url that points to it (nil if parent svg cannot be found). Initializes gradient to use bounding box of object, but using userSpaceOnUse setting

func (*SVG) GradientUpdateAllStops

func (sv *SVG) GradientUpdateAllStops()

GradientUpdateAllStops removes any items from Defs that are not actually referred to by anything in the current SVG tree. Returns true if items were removed. Does not remove gradients with StopsName = "" with extant stops -- these should be removed manually, as they are not automatically generated.

func (*SVG) GradientUpdateNodePoints

func (sv *SVG) GradientUpdateNodePoints(n Node, prop string)

GradientUpdateNodePoints updates the points for node based on current bbox

func (*SVG) GradientUpdateNodeProp

func (sv *SVG) GradientUpdateNodeProp(n Node, prop string, radial bool, stops string) (*Gradient, string)

GradientUpdateNodeProp ensures that node has a gradient property of given type

func (*SVG) GradientUpdateStops

func (sv *SVG) GradientUpdateStops(gr *Gradient)

GradientUpdateStops copies stops from StopsName gradient if it is set

func (*SVG) ImageByURL

func (sv *SVG) ImageByURL(url string) image.Image

ImageByURL finds a Node by an element name (URL-like path), and attempts to convert it to an image.Image. Used for color styling based on url() value.

func (*SVG) MarkerByName

func (sv *SVG) MarkerByName(n Node, marker string) *Marker

MarkerByName finds marker property of given name, or generic "marker" type, and if set, attempts to find that marker and return it

func (*SVG) MarshalXMLx

func (sv *SVG) MarshalXMLx(enc *XMLEncoder, se xml.StartElement) error

MarshalXMLx marshals the svg using XMLEncoder

func (*SVG) NewUniqueID added in v0.0.7

func (sv *SVG) NewUniqueID() int

NewUniqueID returns a new unique numerical id number, for naming an object

func (*SVG) NodeEnsureUniqueId

func (sv *SVG) NodeEnsureUniqueId(ni Node)

NodeEnsureUniqueId ensures that the given node has a unique Id Call this on any newly-created nodes.

func (*SVG) NodeFindURL

func (sv *SVG) NodeFindURL(n Node, url string) Node

NodeFindURL finds a url element in the parent SVG of given node. Returns nil if not found. Works with full 'url(#Name)' string or plain name or "none"

func (*SVG) OpenFS

func (sv *SVG) OpenFS(fsys fs.FS, fname string) error

OpenFS Opens XML-formatted SVG input from given file, filesystem FS

func (*SVG) OpenXML

func (sv *SVG) OpenXML(fname string) error

OpenXML Opens XML-formatted SVG input from given file

func (*SVG) ReadXML

func (sv *SVG) ReadXML(reader io.Reader) error

ReadXML reads XML-formatted SVG input from io.Reader, and uses xml.Decoder to create the SVG scenegraph for corresponding SVG drawing. Removes any existing content in SVG first. To process a byte slice, pass: bytes.NewReader([]byte(str)) -- all errors are logged and also returned.

func (*SVG) RemoveOrphanedDefs

func (sv *SVG) RemoveOrphanedDefs() bool

RemoveOrphanedDefs removes any items from Defs that are not actually referred to by anything in the current SVG tree. Returns true if items were removed. Does not remove gradients with StopsName = "" with extant stops -- these should be removed manually, as they are not automatically generated.

func (*SVG) Render

func (sv *SVG) Render()

func (*SVG) Resize

func (sv *SVG) Resize(nwsz image.Point)

Resize resizes the viewport, creating a new image -- updates Geom Size

func (*SVG) SavePNG

func (sv *SVG) SavePNG(fname string) error

SavePNG saves the Pixels to a PNG file

func (*SVG) SaveXML

func (sv *SVG) SaveXML(fname string) error

SaveXML saves the svg to a XML-encoded file, using WriteXML

func (*SVG) SetDPITransform

func (sv *SVG) SetDPITransform(logicalDPI float32)

SetDPITransform sets a scaling transform to compensate for a given LogicalDPI factor. svg rendering is done within a 96 DPI context.

func (*SVG) SetRootTransform

func (sv *SVG) SetRootTransform()

SetRootTransform sets the Root node transform based on ViewBox, Translate, Scale parameters set on the SVG object.

func (*SVG) SetUnitContext

func (sv *SVG) SetUnitContext(pc *styles.Paint, el, parent math32.Vector2)

SetUnitContext sets the unit context based on size of viewport, element, and parent element (from bbox) and then caches everything out in terms of raw pixel dots for rendering -- call at start of render

func (*SVG) Style

func (sv *SVG) Style()

func (*SVG) UnmarshalXML

func (sv *SVG) UnmarshalXML(decoder *xml.Decoder, se xml.StartElement) error

UnmarshalXML unmarshals the svg using xml.Decoder

func (*SVG) WriteXML

func (sv *SVG) WriteXML(wr io.Writer, indent bool) error

WriteXML writes XML-formatted SVG output to io.Writer, and uses XMLEncoder

type SVGNode

type SVGNode struct {
	Group

	// viewbox defines the coordinate system for the drawing.
	// These units are mapped into the screen space allocated
	// for the SVG during rendering
	ViewBox ViewBox
}

SVGNode represents the root of an SVG tree

func NewSVGNode

func NewSVGNode(parent tree.Node, name ...string) *SVGNode

NewSVGNode adds a new SVGNode with the given name to the given parent: SVGNode represents the root of an SVG tree

func (*SVGNode) EnforceSVGName

func (g *SVGNode) EnforceSVGName() bool

func (*SVGNode) New

func (t *SVGNode) New() tree.Node

New returns a new *SVGNode value

func (*SVGNode) NodeBBox

func (g *SVGNode) NodeBBox(sv *SVG) image.Rectangle

func (*SVGNode) NodeType added in v0.0.10

func (t *SVGNode) NodeType() *types.Type

NodeType returns the *types.Type of SVGNode

func (*SVGNode) SVGName

func (g *SVGNode) SVGName() string

func (*SVGNode) SetClass

func (t *SVGNode) SetClass(v string) *SVGNode

SetClass sets the [SVGNode.Class]

func (*SVGNode) SetViewBox

func (t *SVGNode) SetViewBox(v ViewBox) *SVGNode

SetViewBox sets the [SVGNode.ViewBox]: viewbox defines the coordinate system for the drawing. These units are mapped into the screen space allocated for the SVG during rendering

type StyleSheet

type StyleSheet struct {
	NodeBase
	Sheet *css.Stylesheet `copier:"-"`
}

StyleSheet is a Node2D node that contains a stylesheet -- property values contained in this sheet can be transformed into tree.Properties and set in CSS field of appropriate node

func AddNewStyleSheet

func AddNewStyleSheet(parent tree.Node, name string) *StyleSheet

AddNewStyleSheet adds a new CSS stylesheet to given parent node, with given name.

func NewStyleSheet

func NewStyleSheet(parent tree.Node, name ...string) *StyleSheet

NewStyleSheet adds a new StyleSheet with the given name to the given parent: StyleSheet is a Node2D node that contains a stylesheet -- property values contained in this sheet can be transformed into tree.Properties and set in CSS field of appropriate node

func (*StyleSheet) CSSProperties added in v0.0.10

func (ss *StyleSheet) CSSProperties() map[string]any

CSSProperties returns the properties for each of the rules in this style sheet, suitable for setting the CSS value of a node -- returns nil if empty sheet

func (*StyleSheet) New

func (t *StyleSheet) New() tree.Node

New returns a new *StyleSheet value

func (*StyleSheet) NodeType added in v0.0.10

func (t *StyleSheet) NodeType() *types.Type

NodeType returns the *types.Type of StyleSheet

func (*StyleSheet) ParseString

func (ss *StyleSheet) ParseString(str string) error

ParseString parses the string into a StyleSheet of rules, which can then be used for extracting properties

func (*StyleSheet) SetClass

func (t *StyleSheet) SetClass(v string) *StyleSheet

SetClass sets the [StyleSheet.Class]

func (*StyleSheet) SetSheet

func (t *StyleSheet) SetSheet(v *css.Stylesheet) *StyleSheet

SetSheet sets the [StyleSheet.Sheet]

type Text

type Text struct {
	NodeBase

	// position of the left, baseline of the text
	Pos math32.Vector2 `xml:"{x,y}"`

	// width of text to render if using word-wrapping
	Width float32 `xml:"width"`

	// text string to render
	Text string `xml:"text"`

	// render version of text
	TextRender paint.Text `xml:"-" json:"-" copier:"-"`

	// character positions along X axis, if specified
	CharPosX []float32

	// character positions along Y axis, if specified
	CharPosY []float32

	// character delta-positions along X axis, if specified
	CharPosDX []float32

	// character delta-positions along Y axis, if specified
	CharPosDY []float32

	// character rotations, if specified
	CharRots []float32

	// author's computed text length, if specified -- we attempt to match
	TextLength float32

	// in attempting to match TextLength, should we adjust glyphs in addition to spacing?
	AdjustGlyphs bool

	// last text render position -- lower-left baseline of start
	LastPos math32.Vector2 `xml:"-" json:"-" copier:"-"`

	// last actual bounding box in display units (dots)
	LastBBox math32.Box2 `xml:"-" json:"-" copier:"-"`
}

Text renders SVG text, handling both text and tspan elements. tspan is nested under a parent text -- text has empty Text string.

func NewText

func NewText(parent tree.Node, name ...string) *Text

NewText adds a new Text with the given name to the given parent: Text renders SVG text, handling both text and tspan elements. tspan is nested under a parent text -- text has empty Text string.

func (*Text) ApplyDeltaTransform

func (g *Text) ApplyDeltaTransform(sv *SVG, trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2)

ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node relative to given point. Trans translation and point are in top-level coordinates, so must be transformed into local coords first. Point is upper left corner of selection box that anchors the translation and scaling, and for rotation it is the center point around which to rotate

func (*Text) ApplyTransform

func (g *Text) ApplyTransform(sv *SVG, xf math32.Matrix2)

ApplyTransform applies the given 2D transform to the geometry of this node each node must define this for itself

func (*Text) IsParText

func (g *Text) IsParText() bool

IsParText returns true if this element serves as a parent text element to tspan elements within it. This is true if NumChildren() > 0 and Text == ""

func (*Text) LocalBBox

func (g *Text) LocalBBox() math32.Box2

func (*Text) New

func (t *Text) New() tree.Node

New returns a new *Text value

func (*Text) NodeBBox

func (g *Text) NodeBBox(sv *SVG) image.Rectangle

func (*Text) NodeType added in v0.0.10

func (t *Text) NodeType() *types.Type

NodeType returns the *types.Type of Text

func (*Text) ReadGeom

func (g *Text) ReadGeom(sv *SVG, dat []float32)

ReadGeom reads the geometry of the node from a slice of floating point numbers the length and ordering of which is specific to each node type.

func (*Text) Render

func (g *Text) Render(sv *SVG)

func (*Text) RenderText

func (g *Text) RenderText(sv *SVG)

RenderText renders the text in full coords

func (*Text) SVGName

func (g *Text) SVGName() string

func (*Text) SetAdjustGlyphs

func (t *Text) SetAdjustGlyphs(v bool) *Text

SetAdjustGlyphs sets the [Text.AdjustGlyphs]: in attempting to match TextLength, should we adjust glyphs in addition to spacing?

func (*Text) SetCharPosDX added in v0.0.5

func (t *Text) SetCharPosDX(v ...float32) *Text

SetCharPosDX sets the [Text.CharPosDX]: character delta-positions along X axis, if specified

func (*Text) SetCharPosDY added in v0.0.5

func (t *Text) SetCharPosDY(v ...float32) *Text

SetCharPosDY sets the [Text.CharPosDY]: character delta-positions along Y axis, if specified

func (*Text) SetCharPosX

func (t *Text) SetCharPosX(v ...float32) *Text

SetCharPosX sets the [Text.CharPosX]: character positions along X axis, if specified

func (*Text) SetCharPosY

func (t *Text) SetCharPosY(v ...float32) *Text

SetCharPosY sets the [Text.CharPosY]: character positions along Y axis, if specified

func (*Text) SetCharRots

func (t *Text) SetCharRots(v ...float32) *Text

SetCharRots sets the [Text.CharRots]: character rotations, if specified

func (*Text) SetClass

func (t *Text) SetClass(v string) *Text

SetClass sets the [Text.Class]

func (*Text) SetLastBBox added in v0.0.5

func (t *Text) SetLastBBox(v math32.Box2) *Text

SetLastBBox sets the [Text.LastBBox]: last actual bounding box in display units (dots)

func (*Text) SetLastPos

func (t *Text) SetLastPos(v math32.Vector2) *Text

SetLastPos sets the [Text.LastPos]: last text render position -- lower-left baseline of start

func (*Text) SetNodePos added in v0.0.7

func (g *Text) SetNodePos(pos math32.Vector2)

func (*Text) SetNodeSize added in v0.0.7

func (g *Text) SetNodeSize(sz math32.Vector2)

func (*Text) SetPos

func (t *Text) SetPos(v math32.Vector2) *Text

SetPos sets the [Text.Pos]: position of the left, baseline of the text

func (*Text) SetText

func (t *Text) SetText(v string) *Text

SetText sets the [Text.Text]: text string to render

func (*Text) SetTextLength

func (t *Text) SetTextLength(v float32) *Text

SetTextLength sets the [Text.TextLength]: author's computed text length, if specified -- we attempt to match

func (*Text) SetTextRender

func (t *Text) SetTextRender(v paint.Text) *Text

SetTextRender sets the [Text.TextRender]: render version of text

func (*Text) SetWidth

func (t *Text) SetWidth(v float32) *Text

SetWidth sets the [Text.Width]: width of text to render if using word-wrapping

func (*Text) TextBBox

func (g *Text) TextBBox() math32.Box2

TextBBox returns the bounding box in local coordinates

func (*Text) WriteGeom

func (g *Text) WriteGeom(sv *SVG, dat *[]float32)

WriteGeom writes the geometry of the node to a slice of floating point numbers the length and ordering of which is specific to each node type. Slice must be passed and will be resized if not the correct length.

type ViewBox

type ViewBox struct {

	// offset or starting point in parent Viewport2D
	Min math32.Vector2

	// size of viewbox within parent Viewport2D
	Size math32.Vector2

	// how to scale the view box within parent
	PreserveAspectRatio ViewBoxPreserveAspectRatio
}

ViewBox is used in SVG to define the coordinate system

func (*ViewBox) BoxString added in v0.0.3

func (vb *ViewBox) BoxString() string

BoxString returns the string representation of just the viewbox: "min.X min.Y size.X size.Y"

func (*ViewBox) Defaults

func (vb *ViewBox) Defaults()

Defaults returns viewbox to defaults

func (*ViewBox) String added in v0.0.3

func (vb *ViewBox) String() string

func (*ViewBox) Transform added in v0.0.3

func (vb *ViewBox) Transform(box math32.Vector2) (size, trans, scale math32.Vector2)

Transform returns the transform based on viewbox size relative to given box (viewport) size that it will be rendered into

type ViewBoxAligns added in v0.0.3

type ViewBoxAligns int32 //enums:enum -trim-prefix Align -transform lower

ViewBoxAlign defines values for the PreserveAspectRatio alignment factor

const (
	// align ViewBox.Min with midpoint of Viewport (default)
	AlignMid ViewBoxAligns = iota

	// do not preserve uniform scaling (if either X or Y is None, both are treated as such).
	// In this case, the Meet / Slice value is ignored.
	// This is the same as FitFill from styles.ObjectFits
	AlignNone

	// align ViewBox.Min with top / left of Viewport
	AlignMin

	// align ViewBox.Min+Size with bottom / right of Viewport
	AlignMax
)
const ViewBoxAlignsN ViewBoxAligns = 4

ViewBoxAlignsN is the highest valid value for type ViewBoxAligns, plus one.

func ViewBoxAlignsValues added in v0.0.3

func ViewBoxAlignsValues() []ViewBoxAligns

ViewBoxAlignsValues returns all possible values for the type ViewBoxAligns.

func (ViewBoxAligns) AlignFactor added in v0.0.3

func (va ViewBoxAligns) AlignFactor() float32

AlignFactor returns the alignment factor for proportion offset

func (ViewBoxAligns) Aligns added in v0.0.3

func (va ViewBoxAligns) Aligns() styles.Aligns

Aligns returns the styles.Aligns version of ViewBoxAligns

func (ViewBoxAligns) Desc added in v0.0.3

func (i ViewBoxAligns) Desc() string

Desc returns the description of the ViewBoxAligns value.

func (ViewBoxAligns) Int64 added in v0.0.3

func (i ViewBoxAligns) Int64() int64

Int64 returns the ViewBoxAligns value as an int64.

func (ViewBoxAligns) MarshalText added in v0.0.3

func (i ViewBoxAligns) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*ViewBoxAligns) SetFromAligns added in v0.0.3

func (va *ViewBoxAligns) SetFromAligns(a styles.Aligns)

SetFromAligns sets alignment from the styles.Aligns version of ViewBoxAligns

func (*ViewBoxAligns) SetInt64 added in v0.0.3

func (i *ViewBoxAligns) SetInt64(in int64)

SetInt64 sets the ViewBoxAligns value from an int64.

func (*ViewBoxAligns) SetString added in v0.0.3

func (i *ViewBoxAligns) SetString(s string) error

SetString sets the ViewBoxAligns value from its string representation, and returns an error if the string is invalid.

func (ViewBoxAligns) String added in v0.0.3

func (i ViewBoxAligns) String() string

String returns the string representation of this ViewBoxAligns value.

func (*ViewBoxAligns) UnmarshalText added in v0.0.3

func (i *ViewBoxAligns) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (ViewBoxAligns) Values added in v0.0.3

func (i ViewBoxAligns) Values() []enums.Enum

Values returns all possible values for the type ViewBoxAligns.

type ViewBoxMeetOrSlice

type ViewBoxMeetOrSlice int32 //enums:enum -transform lower

ViewBoxMeetOrSlice defines values for the PreserveAspectRatio meet or slice factor

const (
	// Meet only applies if Align != None (i.e., only for uniform scaling),
	// and means the entire ViewBox is visible within Viewport,
	// and it is scaled up as much as possible to meet the align constraints.
	// This is the same as FitContain from styles.ObjectFits
	Meet ViewBoxMeetOrSlice = iota

	// Slice only applies if Align != None (i.e., only for uniform scaling),
	// and means the entire ViewBox is covered by the ViewBox, and the
	// ViewBox is scaled down as much as possible, while still meeting the
	// align constraints.
	// This is the same as FitCover from styles.ObjectFits
	Slice
)
const ViewBoxMeetOrSliceN ViewBoxMeetOrSlice = 2

ViewBoxMeetOrSliceN is the highest valid value for type ViewBoxMeetOrSlice, plus one.

func ViewBoxMeetOrSliceValues

func ViewBoxMeetOrSliceValues() []ViewBoxMeetOrSlice

ViewBoxMeetOrSliceValues returns all possible values for the type ViewBoxMeetOrSlice.

func (ViewBoxMeetOrSlice) Desc

func (i ViewBoxMeetOrSlice) Desc() string

Desc returns the description of the ViewBoxMeetOrSlice value.

func (ViewBoxMeetOrSlice) Int64

func (i ViewBoxMeetOrSlice) Int64() int64

Int64 returns the ViewBoxMeetOrSlice value as an int64.

func (ViewBoxMeetOrSlice) MarshalText

func (i ViewBoxMeetOrSlice) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*ViewBoxMeetOrSlice) SetInt64

func (i *ViewBoxMeetOrSlice) SetInt64(in int64)

SetInt64 sets the ViewBoxMeetOrSlice value from an int64.

func (*ViewBoxMeetOrSlice) SetString

func (i *ViewBoxMeetOrSlice) SetString(s string) error

SetString sets the ViewBoxMeetOrSlice value from its string representation, and returns an error if the string is invalid.

func (ViewBoxMeetOrSlice) String

func (i ViewBoxMeetOrSlice) String() string

String returns the string representation of this ViewBoxMeetOrSlice value.

func (*ViewBoxMeetOrSlice) UnmarshalText

func (i *ViewBoxMeetOrSlice) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (ViewBoxMeetOrSlice) Values

func (i ViewBoxMeetOrSlice) Values() []enums.Enum

Values returns all possible values for the type ViewBoxMeetOrSlice.

type ViewBoxPreserveAspectRatio

type ViewBoxPreserveAspectRatio struct {

	// how to align X, Y coordinates within viewbox
	Align styles.XY[ViewBoxAligns] `xml:"align"`

	// how to scale the view box relative to the viewport
	MeetOrSlice ViewBoxMeetOrSlice `xml:"meetOrSlice"`
}

ViewBoxPreserveAspectRatio determines how to scale the view box within parent Viewport2D

func (*ViewBoxPreserveAspectRatio) SetFromStyle added in v0.0.3

func (pa *ViewBoxPreserveAspectRatio) SetFromStyle(s *styles.Style)

SetFromStyle sets from ObjectFit and Justify (X) and Align (Y) Content in given style.

func (*ViewBoxPreserveAspectRatio) SetString added in v0.0.3

func (pa *ViewBoxPreserveAspectRatio) SetString(s string) error

SetString sets from a standard svg-formatted string, consisting of: none | x[Min, Mid, Max]Y[Min, Mid, Max] [ meet | slice] e.g., "xMidYMid meet" (default) It does not make sense to specify "meet | slice" for "none" as they do not apply in that case.

func (*ViewBoxPreserveAspectRatio) String added in v0.0.3

func (pa *ViewBoxPreserveAspectRatio) String() string

type XMLEncoder

type XMLEncoder struct {
	Writer      io.Writer
	DoIndent    bool
	IndBytes    []byte
	PreBytes    []byte
	CurIndent   int
	CurStart    string
	NoEndIndent bool
}

XMLEncoder is a minimal XML encoder that formats output with Attr each on a new line, using same API as xml.Encoder

func NewXMLEncoder

func NewXMLEncoder(wr io.Writer) *XMLEncoder

func (*XMLEncoder) EncodeToken

func (xe *XMLEncoder) EncodeToken(t xml.Token) error

func (*XMLEncoder) EscapeString

func (xe *XMLEncoder) EscapeString(s string, escapeNewline bool)

EscapeString writes to p the properly escaped XML equivalent of the plain text data s.

func (*XMLEncoder) Flush

func (xe *XMLEncoder) Flush()

func (*XMLEncoder) Indent

func (xe *XMLEncoder) Indent(prefix, indent string)

func (*XMLEncoder) WriteEOL

func (xe *XMLEncoder) WriteEOL()

func (*XMLEncoder) WriteEnd

func (xe *XMLEncoder) WriteEnd(name string) error

func (*XMLEncoder) WriteIndent

func (xe *XMLEncoder) WriteIndent()

func (*XMLEncoder) WriteStart

func (xe *XMLEncoder) WriteStart(start *xml.StartElement) error

func (*XMLEncoder) WriteString

func (xe *XMLEncoder) WriteString(str string)

Directories

Path Synopsis
cmd
svg

Jump to

Keyboard shortcuts

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