oksvg
| Language | Go |
|---|---|
| License | BSD-3-Clause |
| Repository | github.com/srwiley/oksvg |
| Documentation | pkg.go.dev |
| Depends on | rasterx, golang.org/x/image, golang.org/x/net |
| Read / write | read (renders to any draw.Image) / no |
oksvg parses SVG and draws it with rasterx, a scanline rasterizer that implements SVG 2 stroke features (including the arc line join). It’s pure Go and good enough for most icon sets: paths, basic shapes, groups, transforms, solid colors, linear and radial gradients, opacity and <use>.
It doesn’t render text, images, filters, masks, clipping or patterns, and supports only simple class selectors from a <style> element inside <defs>. Unknown elements cause errors in strict mode. The last changes are from 2022-2023, so treat it as stable but unmaintained. For broader coverage in pure Go see canvas.
Installation#
go get github.com/srwiley/oksvg github.com/srwiley/rasterx
Basic usage: render SVG to PNG#
package main
import (
"fmt"
"image"
"image/png"
"log"
"os"
"github.com/srwiley/oksvg"
"github.com/srwiley/rasterx"
)
func main() {
icon, err := oksvg.ReadIcon("in.svg", oksvg.WarnErrorMode)
if err != nil {
log.Fatal(err)
}
fmt.Printf("viewBox %v x %v\n", icon.ViewBox.W, icon.ViewBox.H)
w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
icon.SetTarget(0, 0, float64(w), float64(h))
img := image.NewRGBA(image.Rect(0, 0, w, h))
scanner := rasterx.NewScannerGV(w, h, img, img.Bounds())
icon.Draw(rasterx.NewDasher(w, h, scanner), 1.0) // 1.0 = full opacity
out, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := png.Encode(out, img); err != nil {
log.Fatal(err)
}
}
How to render an SVG icon at a given size#
SetTarget(x, y, w, h) maps the viewBox to a rectangle in the output image:
size := 256
icon.SetTarget(0, 0, float64(size), float64(size))
img := image.NewRGBA(image.Rect(0, 0, size, size))
icon.Draw(rasterx.NewDasher(size, size, rasterx.NewScannerGV(size, size, img, img.Bounds())), 1.0)
For non-square icons, compute the height from icon.ViewBox.H / icon.ViewBox.W.
How to load SVG from memory#
icon, err := oksvg.ReadIconStream(bytes.NewReader(svgData), oksvg.WarnErrorMode)
How to replace currentColor#
Icon sets often use fill="currentColor". ReadReplacingCurrentColor substitutes a color while parsing:
f, _ := os.Open("icon.svg")
defer f.Close()
icon, err := oksvg.ReadReplacingCurrentColor(f, "#d33", oksvg.WarnErrorMode)
Tips#
- Error modes:
oksvg.StrictErrorModefails on unsupported elements,oksvg.WarnErrorModelogs and continues,oksvg.IgnoreErrorModeskips silently. - Draw onto an existing image (e.g. a background) by passing it as the scanner destination.