All formats

SVGo

LanguageGo
LicenseCreative Commons Attribution 4.0 (a content license, not an OSI-approved software license)
Repositorygithub.com/ajstarks/svgo
Documentationpkg.go.dev
Depends onnothing (standard library)
Read / writeno / yes

SVGo writes SVG 1.1 to an io.Writer (a file, an HTTP response, a buffer). Each SVG element has a method: Rect, Circle, Line, Path, Text, Gid for groups, gradients, filters, patterns, markers and animation. Style is passed as an optional CSS string. It doesn’t build a document tree and doesn’t parse SVG: output goes straight to the writer.

It is old and stable (little has changed since 2022). Check the license before using it: CC BY 4.0 requires attribution and is not designed for software. For an MIT-licensed alternative that also writes PDF and PNG, see canvas.

Installation#

Shell
go get github.com/ajstarks/svgo

The package name is svg.

Basic usage: write an SVG file#

Go
package main

import (
	"log"
	"os"

	svg "github.com/ajstarks/svgo"
)

func main() {
	f, err := os.Create("out.svg")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	canvas := svg.New(f)
	canvas.Start(300, 200)
	canvas.Title("Example")
	canvas.Rect(0, 0, 300, 200, "fill:white")
	canvas.Circle(150, 100, 60, "fill:orange;stroke:black;stroke-width:2")
	canvas.Text(150, 105, "Hello, SVG", "text-anchor:middle;font-size:20px")
	canvas.End()
}

How to group elements and draw paths#

Go
canvas.Gid("bars")
for i, v := range []int{40, 80, 60} {
	canvas.Rect(20+i*30, 180-v, 20, v, "fill:steelblue")
}
canvas.Gend()

canvas.Line(10, 190, 290, 190, "stroke:gray")
canvas.Path("M 220 40 L 280 40 L 250 90 Z", "fill:green")

Gstyle, Gtransform and Translate/Scale/Rotate open groups with a style or transform; close each with Gend.

How to define and use a gradient#

Go
canvas.Def()
canvas.LinearGradient("grad", 0, 0, 100, 0, []svg.Offcolor{
	{Offset: 0, Color: "red", Opacity: 1},
	{Offset: 100, Color: "blue", Opacity: 1},
})
canvas.DefEnd()
canvas.Rect(0, 0, 300, 20, "fill:url(#grad)")

How to serve SVG from an HTTP handler#

Go
func chart(w http.ResponseWriter, r *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()
}

Tips#