svgo

repository·master·Indexed 24 days ago

https://github.com/ajstarks/svgo

A Go library for programmatically generating Scalable Vector Graphics (SVG) following the SVG 1.1 specification. It supports shapes, paths, gradients, transformations, animations, and filter effects. The library includes a floating-point version in the `float` package and a `svgplay` command for live-coding SVG in a browser.

Tokens
7.1K
Snippets
9
Records
40
Agent score
77%

What's inside svgo

  1. Apply styles to SVG elements

    master

    Most drawing functions in SVGo accept an optional variadic argument s ...string to apply styles. These style strings follow the SVG standard and can be provided in two formats:

    1. Semicolon-delimited name:value pairs: "fill:none; opacity:0.3"
    2. Attribute-style name="value" pairs: fill="none" opacity="0.3"

    Example usage in a function call: Circle(x, y, r, "fill:red; stroke:black")

  2. Initialize an SVG document with SVGo

    master

    To start generating an SVG, you must first create an SVG instance by calling New(w io.Writer). Most drawing operations are methods on this type and will write to the provided io.Writer.

    To begin the actual SVG document structure, use one of the following methods depending on your coordinate requirements:

    • Start(w int, h int, attributes ...string): Begins the document with width w and height h.
    • Startview(w, h, minx, miny, vw, vh int): Begins the document with width/height and a viewBox.
    • Startunit(w int, h int, unit string, ns ...string): Begins the document using specific units (e.g., px, cm).
    • Startpercent(w int, h int, ns ...string): Begins the document using percentages.
    • StartviewUnit(w, h int, unit string, minx, miny, vw, vh int): Combines specific units with a viewBox.

    Always call End() to close the SVG document.

  3. Install SVGo

    master

    To use SVGo in your Go projects, install the package using go get and install the associated tools using go install. This assumes your GOPATH is correctly configured.

    go get github.com/ajstarks/svgo
    go install github.com/ajstarks/svgo/...
  4. Sketch SVG with code using svgplay

    master

    You can use the svgplay command to create a live-coding environment in your browser.

    1. Navigate to your code directory.
    2. Run svgplay -f (the -f flag specifies the floating-point version of SVGo).
    3. Open http://localhost:1999/ in your browser.
    4. Enter your Go code in the textarea and press Shift+Enter to run.

    Important: For svgplay to work, the io.Writer passed to svg.New must be os.Stdout. To sketch using an existing file, enter its URL (e.g., http://localhost:1999/foo.go) in the browser.

    $ svgplay -f
  5. Initialize an SVG document with New()

    master

    To start generating an SVG, use svg.New(w io.Writer) to create a new SVG instance. The provided io.Writer (such as os.Stdout or a file) is where the generated XML will be written. You must call a Start method to begin the document and End() to close the <svg> tag.

    import (
    	"github.com/ajstarks/svgo"
    	"os"
    )
    
    var (
    	width = 500
    	height = 500
    	canvas = svg.New(os.Stdout)
    )
    
    func main() {
    	canvas.Start(width, height)
    	// ... drawing commands ...
    	canvas.End()
    }
  6. Generate SVG to standard output

    master

    To generate SVG output to os.Stdout, use svg.New(os.Stdout). You must call .Start(width, height) to initialize the canvas and .End() to finalize the SVG document. All drawing methods (like .Circle or .Text) are called on the canvas instance.

    package main
    
    import (
    	"github.com/ajstarks/svgo"
    	"os"
    )
    
    func main() {
    	width := 500
    	height := 500
    	canvas := svg.New(os.Stdout)
    	canvas.Start(width, height)
    	canvas.Circle(width/2, height/2, 100)
    	canvas.Text(width/2, height/2, "Hello, SVG", "text-anchor:middle;font-size:30px;fill:white")
    	canvas.End()
    }
  7. Serve SVG via an HTTP server

    master

    To serve SVGs dynamically through a web server, initialize svg.New(w) where w is the http.ResponseWriter. Ensure you set the Content-Type header to image/svg+xml before writing the SVG data.

    package main
    
    import (
    	"log"
    	"github.com/ajstarks/svgo"
    	"net/http"
    )
    
    func main() {
    	http.Handle("/circle", http.HandlerFunc(circle))
    	err := http.ListenAndServe(":2003", nil)
    	if err != nil {
    		log.Fatal("ListenAndServe:", err)
    	}
    }
    
    func circle(w http.ResponseWriter, req *http.Request) {
      w.Header().Set("Content-Type", "image/svg+xml")
      s := svg.New(w)
      s.Start(500, 500)
      s.Circle(250, 250, 125, "fill:none;stroke:black")
      s.End()
    }
  8. Draw SVG in a web server

    master

    To serve SVG dynamically via HTTP, create an http.HandlerFunc that sets the Content-Type header to image/svg+xml and passes the http.ResponseWriter to svg.New().

    package main
    
    import (
    	"log"
    	"github.com/ajstarks/svgo/float"
    	"net/http"
    )
    
    func main() {
    	http.Handle("/circle", http.HandlerFunc(circle))
    	err := http.ListenAndServe(":2003", nil)
    	if err != nil {
    		log.Fatal("ListenAndServe:", err)
    	}
    }
    
    func circle(w http.ResponseWriter, req *http.Request) {
    	w.Header().Set("Content-Type", "image/svg+xml")
    	s := svg.New(w)
    	s.Start(500, 500)
    	s.Circle(250, 250, 125, "fill:none;stroke:black")
    	s.End()
    }
  9. Create gradients and colors

    master

    Colors

    Use these functions to generate style strings for colors:

    • RGB(r int, g int, b int) string: Returns an RGB color string.
    • RGBA(r int, g int, b int, a float64) string: Returns an RGBA color string (opacity a between 0.0 and 1.0).

    Gradients

    • LinearGradient(id string, x1, y1, x2, y2 uint8, sc []Offcolor): Constructs a linear gradient identified by id along the vector (x1,y1) to (x2,y2). Coordinates are percentages. sc is a slice of Offcolor structs defining stops.
    • RadialGradient(id string, cx, cy, r, fx, fy uint8, sc []Offcolor): Constructs a radial gradient centered at (cx,cy) with radius r. (fx, fy) defines the focal point. Coordinates are percentages.
  10. Animate SVG elements

    master

    SVGo supports several animation types to animate attributes or transformations:

    • Animate(link, attr string, from, to, duration, repeat float64, s ...string): Animates a specific attribute of the referenced link.
    • AnimateMotion(link, path string, duration, repeat float64, s ...string): Animates an object along a path.
    • AnimateTranslate(link string, fx, fy, tx, ty, duration, repeat float64, s ...string): Animates translation.
    • AnimateRotate(link string, fs, fc, fe, ts, tc, te, duration, repeat float64, s ...string): Animates rotation.
    • AnimateScale(link string, from, to, duration, repeat float64, s ...string): Animates scaling.
    • AnimateSkewX(link string, from, to, duration, repeat float64, s ...string): Animates skewX.
    • AnimateSkewY(link string, from, to, duration, repeat float64, s ...string): Animates skewY.