Categorygithub.com/omniskop/canvas
modulepackage
0.0.0-20231230061527-f3557b44e492
Repository: https://github.com/omniskop/canvas.git
Documentation: pkg.go.dev

# README

Canvas

API reference User guide Go Report Card Coverage Status Donate

API documentation

User guide

Live HTMLCanvas demo

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 bottom-left shows path boolean operations. 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!

State

Whether this library is ready for production environments is up to your own judgment. In general, this library is written thoughtfully and complete, but the scope of this work is so big and the implementation can be quite complex that inevitably it must have a great amount of bugs. Effort was put in writing unit and fuzz tests so that I suspect only special use-cases will stumble into bugs, but coverage is still lacking. As time permits, work is done to flesh-out functionality, find bugs, and optimize code. Optimization could be in execution time / reducing code complexity, reducing memory footprint, or reducing the length of paths from operation.

Please issue bug reports or feature requests to help this library mature! All help is appreciated. Also see Wiki - Planning for an inexhaustive list of ideas and TODOs.

Recent changes

  • Context view and coordinate view have been altered. View now doesn't affect the coordinate view/system. To achieve the same as before, replace ctx.SetView(m) by ctx.SetView(m); ctx.SetCoordView(m). The change makes coordinate systems more intuitive when using in combination with views, the given coordinate reflects the coordinate where it is drawn irrespective of the view.
  • Flatten(), Stroke(), and Offset() now require an additional tolerance variable, which used to be set by the Tolerance parameter with a default value of 0.01. To get the original behaviour, use Flatten(0.01), Stroke(width, capper, joiner, 0.01), and Offset(width, fillRule, 0.01).
  • Interior() is renamed to Fills()
  • ParseSVG and MustParseSVG are now ParseSVGPath and MustParseSVGPath to avoid confusion that it parses entire SVGs
  • Instead of MiterClipJoin(limit) use MiterClipJoiner{nil, limit} or MiterClipJoin to use the default limit of 4.0, same for ArcsClipJoin
  • Path.Segments has been deprecated, please use Path.Scanner
  • *LocalFont have been deprecated, please use *SystemFont
  • RichText.SetFaceSpan has been deprecated
  • RichText.Add has been deprecated, please use RichText.WriteFace
  • RichText.Add* have been deprecated, please use RichText.Write*
  • Path.Complex has been renamed as Path.HasSubpaths

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
  • Path boolean operations: AND, OR, XOR, NOT, Divide
  • 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
  • Rendering targets
    • Raster images (PNG, GIF, JPEG, TIFF, BMP, WEBP)
    • PDF
    • SVG and SVGZ
    • PS and EPS
    • HTMLCanvas
    • OpenGL
  • Rendering sources
    • Canvas itself

Examples

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

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

Text document: an example of a text document using the PDF backend.

OpenGL: an example using the OpenGL backend.

Gio: an example using the Gio backend.

Fyne: an example using the Fyne 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: an example using the go-chart library, plotting a financial graph.

gonum/plot: an example using the gonum/plot library.

HTMLCanvas: an example using the HTMLCanvas backend, see the live demo.

Users

This is a non-exhaustive list of library users I've come across. PRs are welcome to extend the list!

Articles

My own

Papers

License

Released under the MIT license.

Be aware that Fribidi uses the LGPL license.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

Arc returns a circular arc with radius r and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run.
BeveledRectangle returns a rectangle of width w and height h with beveled corners at distance r from the corner.
CacheSystemFonts will write and load the list of system fonts to the given filename.
Circle returns a circle of radius r.
DPI (dots-per-inch) for the resolution of rasterization.
DPMM (dots-per-millimeter) for the resolution of rasterization.
DrawPreview draws the canvas's preview to a Context.
DrawPreviewWithAssets draws the canvas's preview to a Context with assets preloaded.
DVI2Path parses a DVI file (output from TeX) and returns a path.
Ellipse returns an ellipse of radii rx and ry.
EllipsePos returns the position on the ellipse at angle theta.
EllipticalArc returns an elliptical arc with radii rx and ry, with rot the counter clockwise rotation in degrees, and theta0 and theta1 the angles in degrees of the ellipse (before rot is applies) between which the arc will run.
Equal returns true if a and b are Equal with tolerance Epsilon.
FindLocalFont finds the path to a font from the system's fonts.
FindSystemFont finds the path to a font from the system's fonts.
Grid returns a stroked grid of width w and height h, with grid line thickness r, and the number of cells horizontally and vertically as nx and ny respectively.
Hex parses a CSS hexadecimal color such as e.g.
Interval returns true if f is in closed interval [lower-Epsilon,upper+Epsilon] where lower and upper can be interchanged.
IntervalExclusive returns true if f is in open interval [lower+Epsilon,upper-Epsilon] where lower and upper can be interchanged.
Line returns a line segment of from (0,0) to (x,y).
LoadFont loads a font from memory.
LoadFontCollection loads a font from a collection file and uses the font at the specified index.
LoadFontFile loads a font from a file.
LoadLocalFont loads a font from the system's fonts.
LoadSystemFont loads a font from the system's fonts.
MustParseSVGPath parses an SVG path data string and panics if it fails.
New returns a new canvas with width and height in millimeters, that records all drawing operations into layers.
NewContext returns a new context which is a wrapper around a renderer.
NewCrossHatch returns a new cross hatch pattern of two regular line hatches at different angles and with different distance intervals.
NewFontFamily returns a new font family.
NewFontSubsetter returns a new font subsetter.
NewFromSize returns a new canvas of given size in millimeters, that records all drawing operations into layers.
NewHatchPattern returns a new hatch pattern.
NewJPEGImage parses a JPEG image.
NewLinearGradient returns a new linear gradient pattern.
NewLineHatch returns a new line hatch pattern with lines at an angle with a spacing of distance.
NewPNGImage parses a PNG image.
NewRadialGradient returns a new radial gradient pattern.
NewRichText returns a new rich text with the given default font face.
NewShapeHatch returns a new shape hatch that repeats the given shape over a rhombus primitive cell with sides of length distance.
NewTextBox is an advanced text formatter that will format text placement based on the settings.
NewTextLine is a simple text line using a single font face, a string (supporting new lines) and horizontal alignment (Left, Center, Right).
ParallelogramCell is a paralellogram cell with sides of length a and b at an angle of rot degrees used for tiling.
ParseLaTeX parse a LaTeX formula (that what is between $...$) and returns a path.
No description provided by the author
ParseSVGPath parses an SVG path data string.
PolarPoint returns a point from polar coordinates, with angle in radians CCW and radius the distance from (0,0).
PolylineFromPath returns a polyline from the given path by approximating it by linear line segments, i.e.
PolylineFromPathCoords returns a polyline from the given path from each of the start/end coordinates of the segments, i.e.
PrimitiveCell is a (primitive) cell used for tiling.
Rectangle returns a rectangle of width w and height h.
RectangleCell is a rectangular cell with width a and height b used for tiling.
RegularPolygon returns a regular polygon with radius r.
RegularStarPolygon returns a regular star polygon with radius r.
RGB returns a color given by red, green, and blue ∈ [0,255].
RGBA returns a color given by red, green, and blue ∈ [0,255] (non alpha premultiplied) and alpha ∈ [0,1].
RhombusCell is a rhombus cell with sides of length a at an angle of 120 degrees used for tiling.
RoundedRectangle returns a rectangle of width w and height h with rounded corners of radius r.
SquareCell is a square cell with sides of length a used for tiling.
StarPolygon returns a star polygon of n points with alternating radius R and r.
TileRectangle tiles the given cell (determines the axes along which cells are repeated) onto the rectangle dst (bounds of clipping path), where cells are filled by rectangle src (bounds of object to be tiled).
Triangle returns a triangle of radius r pointing upwards.

# Constants

16.0.
see VerticalAlign.
see TextAlign.
See CoordSystem.
See CoordSystem.
See CoordSystem.
See CoordSystem.
see TextAlign.
32.0.
8.0.
DefaultResolution is the default resolution used for font PPEMs and is set to 96 DPI.
see FillRule.
900.
700.
see VerticalAlign.
800.
200.
see FontStyle.
300.
500.
see VerticalAlign.
see FontVariant.
400.
600.
see FontVariant.
see FontVariant.
see FontVariant.
100.
see VerticalAlign.
see WritingMode.
See ImageFit.
See ImageFit.
See ImageFit.
see TextAlign.
see TextAlign.
2.0.
see ImageEncoding.
see ImageEncoding.
see TextAlign.
1.0.
turn horizontal text 90deg clockwise for VerticalRL, and counter clockwise for VerticalLR.
see FillRule.
see FillRule.
see FillRule.
4.0.
see TextAlign.
see TextAlign.
split characters and lay them out upright.
see WritingMode.
see WritingMode.

# Variables

Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
rgb(240, 248, 255).
rgb(250, 235, 215).
rgb(0, 255, 255).
rgb(127, 255, 212).
No description provided by the author
ArcsJoin connects two path elements by extending the ends of the paths as circle arcs until they meet.
rgb(240, 255, 255).
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
rgb(245, 245, 220).
BevelJoin connects two path elements by a linear join.
rgb(255, 228, 196).
rgb(0, 0, 0).
rgb(255, 235, 205).
rgb(0, 0, 255).
rgb(138, 43, 226).
rgb(165, 42, 42).
rgb(222, 184, 135).
ButtCap caps the start or end of a path by a butt cap.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
rgb(95, 158, 160).
rgb(127, 255, 0).
rgb(210, 105, 30).
rgb(255, 127, 80).
rgb(100, 149, 237).
rgb(255, 248, 220).
rgb(220, 20, 60).
rgb(0, 255, 255).
Predefined paper sizes.
rgb(0, 0, 139).
rgb(0, 139, 139).
rgb(184, 134, 11).
rgb(169, 169, 169).
rgb(0, 100, 0).
rgb(169, 169, 169).
rgb(189, 183, 107).
rgb(139, 0, 139).
rgb(85, 107, 47).
rgb(255, 140, 0).
rgb(153, 50, 204).
rgb(139, 0, 0).
rgb(233, 150, 122).
rgb(143, 188, 143).
rgb(72, 61, 139).
rgb(47, 79, 79).
rgb(47, 79, 79).
rgb(0, 206, 209).
rgb(148, 0, 211).
rgb(255, 20, 147).
rgb(0, 191, 255).
DefaultColorSpace is set to LinearColorSpace to match other renderers.
DefaultStyle is the default style for paths.
rgb(105, 105, 105).
rgb(105, 105, 105).
rgb(30, 144, 255).
Epsilon is the smallest number below which we assume the value to be zero.
Predefined paper sizes.
rgb(178, 34, 34).
rgb(255, 250, 240).
FontDashedUnderline is a font decoration that draws a dashed line under the text.
FontDottedUnderline is a font decoration that draws a dotted line under the text.
FontDoubleUnderline is a font decoration that draws two lines under the text.
FontOverline is a font decoration that draws a line over the text.
FontSawtoothUnderline is a font decoration that draws a wavy sawtooth path under the text.
FontSineUnderline is a font decoration that draws a wavy sine path under the text.
FontStrikethrough is a font decoration that draws a line through the text.
FontUnderline is a font decoration that draws a line under the text.
FontWavyUnderline is a font decoration that draws a wavy path under the text.
rgb(34, 139, 34).
rgb(255, 0, 255).
rgb(220, 220, 220).
rgb(248, 248, 255).
rgb(255, 215, 0).
rgb(218, 165, 32).
rgb(128, 128, 128).
rgb(0, 128, 0).
rgb(173, 255, 47).
rgb(128, 128, 128).
rgb(240, 255, 240).
rgb(255, 105, 180).
Identity is the identity affine transformation matrix, i.e.
rgb(205, 92, 92).
rgb(75, 0, 130).
rgb(255, 255, 240).
rgb(240, 230, 140).
rgb(230, 230, 250).
rgb(255, 240, 245).
rgb(124, 252, 0).
Predefined paper sizes.
Predefined paper sizes.
rgb(255, 250, 205).
Predefined paper sizes.
rgb(173, 216, 230).
rgb(240, 128, 128).
rgb(224, 255, 255).
rgb(250, 250, 210).
rgb(211, 211, 211).
rgb(144, 238, 144).
rgb(211, 211, 211).
rgb(255, 182, 193).
rgb(255, 160, 122).
rgb(32, 178, 170).
rgb(135, 206, 250).
rgb(119, 136, 153).
rgb(119, 136, 153).
rgb(176, 196, 222).
rgb(255, 255, 224).
rgb(0, 255, 0).
rgb(50, 205, 50).
rgb(250, 240, 230).
rgb(255, 0, 255).
rgb(128, 0, 0).
rgb(102, 205, 170).
rgb(0, 0, 205).
rgb(186, 85, 211).
rgb(147, 112, 219).
rgb(60, 179, 113).
rgb(123, 104, 238).
rgb(0, 250, 154).
rgb(72, 209, 204).
rgb(199, 21, 133).
rgb(25, 25, 112).
rgb(245, 255, 250).
rgb(255, 228, 225).
No description provided by the author
MiterJoin connects two path elements by extending the ends of the paths as lines until they meet.
rgb(255, 228, 181).
rgb(255, 222, 173).
rgb(0, 0, 128).
rgb(253, 245, 230).
rgb(128, 128, 0).
rgb(107, 142, 35).
rgb(255, 165, 0).
rgb(255, 69, 0).
rgb(218, 112, 214).
Origin is the coordinate system's origin.
rgb(238, 232, 170).
rgb(152, 251, 152).
rgb(175, 238, 238).
rgb(219, 112, 147).
rgb(255, 239, 213).
rgb(255, 218, 185).
rgb(205, 133, 63).
rgb(255, 192, 203).
PixelTolerance is the maximum deviation of the rasterized path from the original for flattening purposed in pixels.
rgb(221, 160, 221).
rgb(176, 224, 230).
Precision is the number of significant digits at which floating point value will be printed to output formats.
rgb(128, 0, 128).
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
rgb(255, 0, 0).
rgb(188, 143, 143).
RoundCap caps the start or end of a path by a round cap.
RoundJoin connects two path elements by a round join.
rgb(65, 105, 225).
rgb(139, 69, 19).
rgb(250, 128, 114).
rgb(244, 164, 96).
rgb(46, 139, 87).
rgb(255, 245, 238).
rgb(160, 82, 45).
rgb(192, 192, 192).
rgb(135, 206, 235).
rgb(106, 90, 205).
rgb(112, 128, 144).
rgb(112, 128, 144).
rgb(255, 250, 250).
rgb(0, 255, 127).
SquareCap caps the start or end of a path by a square cap.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
Predefined paper sizes.
rgb(70, 130, 180).
Predefined paper sizes.
rgb(210, 180, 140).
rgb(0, 128, 128).
rgb(216, 191, 216).
Tolerance is the maximum deviation from the original path in millimeters when e.g.
rgb(255, 99, 71).
rgba(0, 0, 0, 0).
rgb(64, 224, 208).
rgb(238, 130, 238).
rgb(245, 222, 179).
rgb(255, 255, 255).
rgb(245, 245, 245).
rgb(255, 255, 0).
rgb(154, 205, 50).

# Structs

ArcsJoiner is an arcs joiner.
BevelJoiner is a bevel joiner.
ButtCapper is a butt capper.
Canvas stores all drawing operations as layers that can be re-rendered to other renderers.
Context maintains the state for the current path, path style, and view transformation matrix.
ContextState defines the state of the context, including fill or stroke style, view and coordinate view.
Font defines an SFNT font such as TTF or OTF.
FontFace defines a font face from a given font.
FontFamily contains a family of fonts (bold, italic, ...).
FontMetrics contains a number of metrics that define a font face.
FontSubsetter holds a map between original glyph IDs and new glyph IDs in a subsetted font.
GammaColorSpace assumes that input colors and output images are gamma-corrected with the given gamma value.
Hatch pattern is a filling hatch pattern.
Image is a raster image.
Intersection is an intersection between two path segments, e.g.
LinearColorSpace is the default color space that does not do color space conversion for blending purposes.
LinearGradient is a linear gradient pattern between the given start and end points.
MiterJoiner is a miter joiner.
Paint is the type of paint used to fill or stroke a path.
Path defines a vector path in 2D using a series of commands (MoveTo, LineTo, QuadTo, CubeTo, ArcTo and Close).
PathIntersection is an intersection of a path.
No description provided by the author
PathReverseScanner scans the path in reverse order.
PathScanner scans the path.
Point is a coordinate in 2D space.
Polyline defines a list of points in 2D space that form a polyline.
RadialGradient is a radial gradient pattern between two circles defined by their center points and radii.
Rect is a rectangle in 2D defined by a position and its width and height.
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.
RoundCapper is a round capper.
RoundJoiner is a round joiner.
Segment is a path command.
Size defines a size (width and height).
SquareCapper is a square capper.
SRGBColorSpace assumes that input colors and output images are in the sRGB color space (ubiquitous in almost all applications), which implies that for blending we need to convert to the linear color space, do blending, and then convert back to the sRGB color space.
Stop is a color and offset for gradient patterns.
Style is the path style that defines how to draw the path.
Text holds the representation of a text object.
TextSpan is a span of text.
TextSpanObject is an object that can be used within a text span.

# Interfaces

Capper implements Cap, with rhs the path to append to, halfWidth the half width of the stroke, pivot the pivot point around which to construct a cap, and n0 the normal at the start of the path.
ColorSpace defines the color space within the RGB color model.
DVIFont draws a rune/glyph to the Pather at a position in millimeters.
DVIFonts gets a font according to its font name and font size in points.
FontDecorator is an interface that returns a path given a font face and a width in millimeters.
Gradient is a gradient pattern for filling.
Joiner implements Join, with rhs the right path and lhs the left path to append to, pivot the intersection of both path elements, n0 and n1 the normals at the start and end of the path respectively.
No description provided by the author
Renderer is an interface that renderers implement.

# Type aliases

CoordSystem is the coordinate system, which can be either of the four cartesian quadrants.
CSSColor is a string formatter to convert a color.RGBA to a CSS color (hexadecimal or using rgba()).
FillRule is the algorithm to specify which area is to be filled and which not, in particular when multiple subpaths overlap.
FontStyle defines the font style to be used for the font.
FontVariant defines the font variant to be used for the font, such as subscript or smallcaps.
Hatcher is a hatch pattern along the cell's axes.
ImageEncoding defines whether the embedded image shall be embedded as lossless (typically PNG) or lossy (typically JPG).
ImageFit specifies how an image should fit a rectangle.
No description provided by the author
Matrix is used for affine transformations, which are transformations such as translation, scaling, reflection, rotation, shear stretching.
Resolution is used for rasterizing.
Stops are the colors and offsets for gradient patterns, sorted by offset.
TextAlign specifies how the text should align or whether it should be justified.
TextOrientation specifies how horizontal text should be oriented within vertical text, or how vertical-only text should be laid out in horizontal text.
VerticalAlign specifies how the object should align vertically when embedded in text.
Writer can write a canvas to a writer.
WritingMode specifies how the text lines should be laid out.