All formats

canvas

LanguageGo
LicenseMIT
Repositorygithub.com/tdewolff/canvas
Documentationpkg.go.dev/github.com/tdewolff/canvas, renderers/ps
Depends onpure Go
Read / writeno / yes (EPS and PostScript)

canvas draws paths, text (TrueType/OpenType fonts, embedded) and images on a canvas measured in millimeters, then writes it through a renderer. The renderers/ps package writes PostScript or, with Format: ps.EncapsulatedPostScript, EPS whose bounding box is the canvas size. c.Fit(margin) shrinks the canvas to the drawing first, so the EPS is cropped tightly.

The EPS renderer can’t express transparency. canvas has no tagged releases; go get uses the latest commit.

Installation#

Shell
go get github.com/tdewolff/canvas

Basic usage: draw a logo and save it as EPS#

Go
package main

import (
	"log"

	"github.com/tdewolff/canvas"
	"github.com/tdewolff/canvas/renderers"
)

func main() {
	c := canvas.New(100, 50) // millimeters
	ctx := canvas.NewContext(c)

	ctx.SetFillColor(canvas.Steelblue)
	ctx.DrawPath(5, 5, canvas.Circle(20))           // origin is bottom-left
	ctx.SetFillColor(canvas.Red)
	ctx.DrawPath(50, 10, canvas.Rectangle(40, 30))

	c.Fit(2) // crop to the drawing plus a 2 mm margin
	if err := c.WriteFile("logo.eps", renderers.EPS()); err != nil {
		log.Fatal(err)
	}
}

renderers.Write("logo.eps", c) does the same, choosing EPS from the extension.

How to add text#

Go
family := canvas.NewFontFamily("sans")
if err := family.LoadFontFile("DejaVuSans.ttf", canvas.FontRegular); err != nil {
	log.Fatal(err)
}
face := family.Face(24, canvas.Black, canvas.FontRegular, canvas.FontNormal) // points
ctx.DrawText(10, 40, canvas.NewTextLine(face, "LOGO", canvas.Left))

How to write EPS to an io.Writer#

Go
import "github.com/tdewolff/canvas/renderers/ps"

var buf bytes.Buffer
r := ps.New(&buf, 100, 50, &ps.Options{Format: ps.EncapsulatedPostScript})
ctx := canvas.NewContext(r)
ctx.DrawPath(10, 10, canvas.Rectangle(80, 30))
if err := r.Close(); err != nil {
	log.Fatal(err)
}

How to export the same drawing as EPS, PDF and SVG#

Go
for _, name := range []string{"logo.eps", "logo.pdf", "logo.svg"} {
	if err := renderers.Write(name, c); err != nil {
		log.Fatal(err)
	}
}

Tips#