canvas

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2021 License: MIT Imports: 12 Imported by: 0

README

Canvas

API reference User guide Go Report Card Coverage Status Donate

Canvas is a common vector drawing target that can output SVG, PDF, EPS, raster images (PNG, JPG, GIF, ...), HTML Canvas through WASM, OpenGL, and Gio. It has a wide range of path manipulation functionality such as flattening, stroking and dashing implemented. Additionally, it has a text formatter and embeds and subsets fonts (TTF, OTF, WOFF, WOFF2, or EOT) or converts them to outlines. It can be considered a Cairo or node-canvas alternative in Go. See the example below in Figure 1 for an overview of the functionality.

Preview

Figure 1: top-left you can see text being fitted into a box, justified using Donald Knuth's linea breaking algorithm to stretch the spaces between words to fill the whole width. You can observe a variety of styles and text decorations applied, as well as support for LTR/RTL mixing and complex scripts. In the bottom-right the word "stroke" is being stroked and drawn as a path. Top-right we see a LaTeX formula that has been converted to a path. Left of that we see an ellipse showcasing precise dashing, notably the length of e.g. the short dash is equal wherever it is on the curve. Note that the dashes themselves are elliptical arcs as well (thus exactly precise even if magnified greatly). To the right we see a closed polygon of four points being smoothed by cubic Béziers that are smooth along the whole path, and the blue line on the left shows a smoothed open path. On the bottom you can see a rotated rasterized image. The result is equivalent for all renderers (PNG, PDF, SVG, etc.).

Sponsors

Please see https://www.patreon.com/tdewolff for ways to contribute, otherwise please contact me directly!

Recent changes

  • Renderers have been moved from github.com/blackss2/canvas/. to github.com/blackss2/canvas/renderers/.
  • FontFamily.Use() is deprecated, use FontFamily.SetFeatures() (not yet used)
  • DPMM is now a function just like DPI: rasterizer.PNGWriter(5.0 * canvas.DPMM) => rasterizer.PNGWriter(canvas.DPMM(5.0))
  • FontFace is now passed around as a pointer
  • NewRichText now requires a default *FontFace to be passed
  • Use the latex build tag to use the original LaTeX expression parser
  • Renderer writers have been moved from renderers/ABC/abc.Writer to renderers/ABC
  • rasterizer.New is renamed to rasterizer.FromImage

Features

  • Path segment types: MoveTo, LineTo, QuadTo, CubeTo, ArcTo, Close
  • Precise path flattening, stroking, and dashing for all segment type uing papers (see below)
  • Smooth spline generation through points for open and closed paths
  • LaTeX to path conversion (native Go and CGO implementations available)
  • Font formats support
    • SFNT (such as TTF, OTF, WOFF, WOFF2, EOT) supporting TrueType, CFF, and CFF2 tables
  • HarfBuzz for text shaping (native Go and CGO implementations available)
  • FriBidi for text bidirectionality (native Go and CGO implementations available)
  • Donald Knuth's line breaking algorithm for text layout
  • sRGB compliance (use SRGBColorSpace, only available for rasterizer)
  • Font rendering with gamma correction of 1.43 (WIP)
  • Rendering targets
    • Raster images (PNG, GIF, JPEG, TIFF, BMP, WEBP)
    • PDF
    • SVG and SVGZ
    • PS and EPS
    • HTMLCanvas
    • OpenGL
  • Rendering sources
    • Canvas itself

Documentation

API documentation

User guide

Examples

Street Map: the centre of Amsterdam is drawn from data loaded from the Open Street Map API.

Mauna-Loa CO2 conentration: using data from the Mauna-Loa observatory, carbon dioxide concentrations over time are drawn

Document: an example of a text document.

OpenGL: an example using the OpenGL backend.

Gio: an example using the Gio backend.

TeX/PGF: an example showing the usage of the PGF (TikZ) LaTeX package as renderer in order to generated a PDF using LaTeX.

go-chart: example usage of the go-chart library, plotting a financial graph.

gonum/plot: example usage of the gonum/plot library.

Articles

My own

Papers

License

Released under the MIT license.

Documentation

Index

Constants

View Source
const DefaultResolution = Resolution(96.0 * inchPerMm)

DefaultResolution is the default resolution used for font PPEMs and is set to 96 DPI.

Variables

This section is empty.

Functions

This section is empty.

Types

type Font

type Font struct {
	*font.SFNT
	// contains filtered or unexported fields
}

Font defines an SFNT font such as TTF or OTF.

func (*Font) Destroy

func (f *Font) Destroy()

Destroy should be called when using HarfBuzz to free the C resources.

func (*Font) Name

func (f *Font) Name() string

Name returns the name of the font.

func (*Font) SetFeatures

func (f *Font) SetFeatures(features string)

SetFeatures sets the font features (not yet supported).

func (*Font) SetVariations

func (f *Font) SetVariations(variations string)

SetVariations sets the font variations (not yet supported).

func (*Font) Style

func (f *Font) Style() FontStyle

Style returns the style of the font.

func (*Font) SubsetID

func (f *Font) SubsetID(glyphID uint16) uint16

SubsetID maps a glyphID of the original font to the subsetted font. If the glyphID is not subsetted, it will be added to the map.

func (*Font) SubsetIDs

func (f *Font) SubsetIDs() []uint16

SubsetIDs returns all subsetted IDs in the order of appearance.

type FontFace

type FontFace struct {
	Font *Font

	Size    float64 // in pt
	Style   FontStyle
	Variant FontVariant

	Color color.RGBA

	// faux styles for bold, italic, and sub- and superscript
	FauxBold, FauxItalic float64
	XOffset, YOffset     int32

	Language  string
	Script    text.Script
	Direction text.Direction
	// contains filtered or unexported fields
}

FontFace defines a font face from a given font. It specifies the font size, color, faux styles and font decorations.

func (*FontFace) Equals

func (face *FontFace) Equals(other *FontFace) bool

Equals returns true when two font face are equal.

func (*FontFace) Metrics

func (face *FontFace) Metrics() FontMetrics

Metrics returns the font metrics. See https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyph_metrics_2x.png for an explanation of the different metrics.

func (*FontFace) Name

func (face *FontFace) Name() string

Name returns the name of the underlying font.

func (*FontFace) PPEM

func (face *FontFace) PPEM(resolution Resolution) uint16

PPEM returns the pixels-per-EM for a given resolution of the font face.

func (*FontFace) TextWidth

func (face *FontFace) TextWidth(s string) float64

TextWidth returns the width of a given string in millimeters.

type FontFamily

type FontFamily struct {
	// contains filtered or unexported fields
}

FontFamily contains a family of fonts (bold, italic, ...). Allowing to select an italic style as the native italic font or to use faux italic if not present.

func NewFontFamily

func NewFontFamily(name string) *FontFamily

NewFontFamily returns a new font family.

func (*FontFamily) Destroy

func (family *FontFamily) Destroy()

Destroy should be called when using HarfBuzz to free the C resources.

func (*FontFamily) Face

func (family *FontFamily) Face(size float64, col color.Color, style FontStyle, variant FontVariant) *FontFace

Face gets the font face given by the font size in points and its style.

func (*FontFamily) FindLocalFont

func (family *FontFamily) FindLocalFont(name string, style FontStyle) string

FindLocalFont finds the path to a font from the system's fonts.

func (*FontFamily) LoadFont

func (family *FontFamily) LoadFont(b []byte, index int, style FontStyle) error

LoadFont loads a font from memory.

func (*FontFamily) LoadFontCollection

func (family *FontFamily) LoadFontCollection(filename string, index int, style FontStyle) error

LoadFontCollection loads a font from a collection file and uses the font at the specified index.

func (*FontFamily) LoadFontFile

func (family *FontFamily) LoadFontFile(filename string, style FontStyle) error

LoadFontFile loads a font from a file.

func (*FontFamily) LoadLocalFont

func (family *FontFamily) LoadLocalFont(name string, style FontStyle) error

LoadLocalFont loads a font from the system's fonts.

func (*FontFamily) Name

func (family *FontFamily) Name() string

Name returns the name of the font family.

func (*FontFamily) SetFeatures

func (family *FontFamily) SetFeatures(features string)

SetFeatures sets the font features (not yet supported).

func (*FontFamily) SetVariations

func (family *FontFamily) SetVariations(variations string)

SetVariations sets the font variations (not yet supported).

type FontMetrics

type FontMetrics struct {
	LineHeight float64
	Ascent     float64
	Descent    float64
	LineGap    float64
	XHeight    float64
	CapHeight  float64

	XMin, YMin float64
	XMax, YMax float64
}

FontMetrics contains a number of metrics that define a font face. See https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyph_metrics_2x.png for an explanation of the different metrics.

func (FontMetrics) String

func (m FontMetrics) String() string

type FontStyle

type FontStyle int

FontStyle defines the font style to be used for the font. It specifies a boldness with optionally italic, e.g. FontBlack | FontItalic will specify a black boldness (a font-weight of 800 in CSS) and italic.

const (
	FontRegular    FontStyle = iota // 400
	FontExtraLight                  // 100
	FontLight                       // 200
	FontBook                        // 300
	FontMedium                      // 500
	FontSemibold                    // 600
	FontBold                        // 700
	FontBlack                       // 800
	FontExtraBlack                  // 900
	FontItalic     FontStyle = 1 << 8
)

see FontStyle

func (FontStyle) CSS

func (style FontStyle) CSS() int

CSS returns the CSS boldness value for the font face.

func (FontStyle) Italic

func (style FontStyle) Italic() bool

Italic returns true if italic.

func (FontStyle) Weight

func (style FontStyle) Weight() FontStyle

Weight returns the font weight (FontRegular, FontBold, ...)

type FontVariant

type FontVariant int

FontVariant defines the font variant to be used for the font, such as subscript or smallcaps.

const (
	FontNormal FontVariant = iota
	FontSubscript
	FontSuperscript
	FontSmallcaps
)

see FontVariant

type Rect

type Rect struct {
	X, Y, W, H float64
}

Rect is a rectangle in 2D defined by a position and its width and height.

func (Rect) Add

func (r Rect) Add(q Rect) Rect

Add returns a rect that encompasses both the current rect and the given rect.

type Resolution

type Resolution float64

Resolution is used for rasterizing. Higher resolutions will result in larger images.

func DPI

func DPI(dpi float64) Resolution

DPI (dots-per-inch) for the resolution of rasterization.

func DPMM

func DPMM(dpmm float64) Resolution

DPMM (dots-per-millimeter) for the resolution of rasterization.

func (Resolution) DPI

func (res Resolution) DPI() float64

DPI returns the resolution in dots-per-inch.

func (Resolution) DPMM

func (res Resolution) DPMM() float64

DPMM returns the resolution in dots-per-millimeter.

type RichText

type RichText struct {
	*strings.Builder
	// contains filtered or unexported fields
}

RichText allows to build up a rich text with text spans of different font faces and fitting that into a box using Donald Knuth's line breaking algorithm. TODO: RichText add support for decoration spans to properly underline the spaces betwee words too

func NewRichText

func NewRichText(face *FontFace) *RichText

NewRichText returns a new rich text with the given default font face.

func (*RichText) Add

func (rt *RichText) Add(face *FontFace, text string) *RichText

Add adds a string with a given font face to the rich text.

func (*RichText) Reset

func (rt *RichText) Reset()

Reset resets the rich text to its initial state.

func (*RichText) SetFace

func (rt *RichText) SetFace(face *FontFace)

SetFace sets the font face.

func (*RichText) SetFaceSpan

func (rt *RichText) SetFaceSpan(face *FontFace, start, end int)

SetFaceSpan sets the font face between start and end measured in bytes.

func (*RichText) SetWritingMode

func (rt *RichText) SetWritingMode(mode WritingMode)

SetWritingMode sets the final writing mode of the rich text.

func (*RichText) ToText

func (rt *RichText) ToText(width, height float64, halign, valign TextAlign, indent, lineStretch float64) *Text

ToText takes the added text spans and fits them within a given box of certain width and height using Donald Knuth's line breaking algorithm.

type Text

type Text struct {
	Face *FontFace
	Mode WritingMode
	// contains filtered or unexported fields
}

Text holds the representation of a text object.

func NewTextBox

func NewTextBox(face *FontFace, s string, width, height float64, halign, valign TextAlign, indent, lineStretch float64) *Text

NewTextBox is an advanced text formatter that will format text placement based on the settings. It takes a single font face, a string, the width or height of the box (can be zero to disable), horizontal and vertical alignment (Left, Center, Right, Top, Bottom or Justify), text indentation for the first line and line stretch (percentage to stretch the line based on the line height).

func NewTextLine

func NewTextLine(face *FontFace, s string, halign TextAlign) *Text

NewTextLine is a simple text line using a single font face, a string (supporting new lines) and horizontal alignment (Left, Center, Right). The text's baseline will be drawn on the current coordinate.

func (*Text) Bounds

func (t *Text) Bounds() Rect

Bounds returns the bounding rectangle that defines the text box.

func (*Text) Empty

func (t *Text) Empty() bool

Empty returns true if there are no text lines or text spans.

func (*Text) Fonts

func (t *Text) Fonts() []*Font

Fonts returns the list of fonts used.

func (*Text) Heights

func (t *Text) Heights() (float64, float64)

Heights returns the top and bottom position of the first and last line respectively.

func (*Text) LineCount added in v1.0.1

func (t *Text) LineCount() int

Lines returns a number of lines

func (*Text) MaxWordCountPerLine added in v1.0.2

func (t *Text) MaxWordCountPerLine() int

MaxWordCountPerLine returns a maximum number of words in a line

type TextAlign

type TextAlign int

TextAlign specifies how the text should align or whether it should be justified.

const (
	Left TextAlign = iota
	Right
	Center
	Top
	Bottom
	Justify
)

see TextAlign

func (TextAlign) String

func (ta TextAlign) String() string

type TextSpan

type TextSpan struct {
	Width     float64
	Face      *FontFace
	Text      string
	Glyphs    []canvasText.Glyph
	Direction canvasText.Direction
	// contains filtered or unexported fields
}

TextSpan is a span of text.

type WritingMode

type WritingMode int

WritingMode specifies how the text lines should be laid out.

const (
	HorizontalTB WritingMode = iota
	VerticalRL
	VerticalLR
)

see WritingMode

func (WritingMode) String

func (wm WritingMode) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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