gg

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 7 Imported by: 8

README

gg - Pure Go 2D Graphics Library

Go Reference Go Report Card CI

A simple, elegant 2D graphics library for Go, inspired by fogleman/gg and designed to integrate with the GoGPU ecosystem.

Features

  • Simple API - Immediate-mode drawing API similar to HTML Canvas
  • Pure Go - No C dependencies (v0.1 software renderer)
  • fogleman/gg compatible - Easy migration from existing code
  • Dual Renderer - Software (v0.1) + GPU-accelerated (v0.3+)
  • Rich Shapes - Rectangles, circles, ellipses, polygons, arcs, Bezier curves
  • Transformations - Translate, rotate, scale, shear with matrix stack
  • Zero Dependencies - Software renderer has no external dependencies

Installation

go get github.com/gogpu/gg

Requirements: Go 1.25+

Quick Start

package main

import (
    "github.com/gogpu/gg"
    "log"
)

func main() {
    // Create a 512x512 context
    ctx := gg.NewContext(512, 512)

    // Clear with white background
    ctx.ClearWithColor(gg.White)

    // Draw a red circle
    ctx.SetRGB(1, 0, 0)
    ctx.DrawCircle(256, 256, 100)
    ctx.Fill()

    // Save to PNG
    if err := ctx.SavePNG("output.png"); err != nil {
        log.Fatal(err)
    }
}

Part of GoGPU Ecosystem

This library is part of the GoGPU project.


Status: v0.1.0-alpha - API unstable, production use not recommended yet.

Documentation

Overview

Package gg provides a simple 2D graphics library for Go.

Overview

gg is a Pure Go 2D graphics library inspired by fogleman/gg and designed to integrate with the GoGPU ecosystem. It provides an immediate-mode drawing API similar to HTML Canvas, with both software and GPU rendering backends.

Quick Start

import "github.com/gogpu/gg"

// Create a context
ctx := gg.NewContext(512, 512)

// Draw shapes
ctx.SetRGB(1, 0, 0)
ctx.DrawCircle(256, 256, 100)
ctx.Fill()

// Save to PNG
ctx.SavePNG("output.png")

API Compatibility

The API is designed to be compatible with fogleman/gg for easy migration. Most fogleman/gg code should work with minimal changes.

Renderers

v0.1.0 includes a software rasterizer for immediate usability. Future versions will add GPU-accelerated rendering via gogpu/wgpu.

Architecture

The library is organized into:

  • Public API: Context, Path, Paint, Matrix, Point
  • Internal: raster (scanline), path (tessellation), blend (compositing)
  • Renderers: software (v0.1), gpu (v0.3+)

Coordinate System

Uses standard computer graphics coordinates:

  • Origin (0,0) at top-left
  • X increases right
  • Y increases down
  • Angles in radians, 0 is right, increases counter-clockwise

Performance

The software renderer is optimized for correctness over speed. For performance-critical applications, use the GPU renderer (v0.3+).

Index

Constants

View Source
const (
	// Version is the current version of the library
	Version = "0.1.0-alpha.1"

	// VersionMajor is the major version
	VersionMajor = 0

	// VersionMinor is the minor version
	VersionMinor = 1

	// VersionPatch is the patch version
	VersionPatch = 0

	// VersionPrerelease is the prerelease identifier
	VersionPrerelease = "alpha.1"
)

Version information

Variables

View Source
var (
	Black       = RGB(0, 0, 0)
	White       = RGB(1, 1, 1)
	Red         = RGB(1, 0, 0)
	Green       = RGB(0, 1, 0)
	Blue        = RGB(0, 0, 1)
	Yellow      = RGB(1, 1, 0)
	Cyan        = RGB(0, 1, 1)
	Magenta     = RGB(1, 0, 1)
	Transparent = RGBA2(0, 0, 0, 0)
)

Common colors

Functions

This section is empty.

Types

type Close

type Close struct{}

Close closes the current subpath.

type Context

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

Context is the main drawing context. It maintains a pixmap, current path, paint state, and transformation stack.

func NewContext

func NewContext(width, height int) *Context

NewContext creates a new drawing context with the given dimensions.

func NewContextForImage

func NewContextForImage(img image.Image) *Context

NewContextForImage creates a context for drawing on an existing image.

func (*Context) Clear

func (c *Context) Clear()

Clear fills the entire context with a color.

func (*Context) ClearPath

func (c *Context) ClearPath()

ClearPath clears the current path.

func (*Context) ClearWithColor

func (c *Context) ClearWithColor(col RGBA)

ClearWithColor fills the entire context with a specific color.

func (*Context) ClosePath

func (c *Context) ClosePath()

ClosePath closes the current subpath.

func (*Context) CubicTo

func (c *Context) CubicTo(c1x, c1y, c2x, c2y, x, y float64)

CubicTo adds a cubic Bezier curve to the current path.

func (*Context) DrawArc

func (c *Context) DrawArc(x, y, r, angle1, angle2 float64)

DrawArc draws a circular arc.

func (*Context) DrawCircle

func (c *Context) DrawCircle(x, y, r float64)

DrawCircle draws a circle.

func (*Context) DrawEllipse

func (c *Context) DrawEllipse(x, y, rx, ry float64)

DrawEllipse draws an ellipse.

func (*Context) DrawEllipticalArc

func (c *Context) DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)

DrawEllipticalArc draws an elliptical arc (advanced).

func (*Context) DrawLine

func (c *Context) DrawLine(x1, y1, x2, y2 float64)

DrawLine draws a line between two points.

func (*Context) DrawPoint

func (c *Context) DrawPoint(x, y, r float64)

DrawPoint draws a single point at the given coordinates.

func (*Context) DrawRectangle

func (c *Context) DrawRectangle(x, y, w, h float64)

DrawRectangle draws a rectangle.

func (*Context) DrawRegularPolygon

func (c *Context) DrawRegularPolygon(n int, x, y, r, rotation float64)

DrawRegularPolygon draws a regular polygon with n sides.

func (*Context) DrawRoundedRectangle

func (c *Context) DrawRoundedRectangle(x, y, w, h, r float64)

DrawRoundedRectangle draws a rectangle with rounded corners.

func (*Context) DrawString

func (c *Context) DrawString(s string, x, y float64)

DrawString is a placeholder for future text rendering.

func (*Context) DrawStringAnchored

func (c *Context) DrawStringAnchored(s string, x, y, ax, ay float64)

DrawStringAnchored is a placeholder for future text rendering with anchoring.

func (*Context) Fill

func (c *Context) Fill()

Fill fills the current path.

func (*Context) FillPreserve

func (c *Context) FillPreserve()

FillPreserve fills the current path and preserves it for additional operations.

func (*Context) Height

func (c *Context) Height() int

Height returns the height of the context.

func (*Context) Identity

func (c *Context) Identity()

Identity resets the transformation matrix to identity.

func (*Context) Image

func (c *Context) Image() image.Image

Image returns the context's image.

func (*Context) InvertY

func (c *Context) InvertY()

InvertY inverts the Y axis (useful for coordinate system changes).

func (*Context) LineTo

func (c *Context) LineTo(x, y float64)

LineTo adds a line to the current path.

func (*Context) LoadFontFace

func (c *Context) LoadFontFace(path string, points float64) error

LoadFontFace is a placeholder for future font loading.

func (*Context) MeasureString

func (c *Context) MeasureString(s string) (w, h float64)

MeasureString is a placeholder for future text measurement.

func (*Context) MoveTo

func (c *Context) MoveTo(x, y float64)

MoveTo starts a new subpath at the given point.

func (*Context) NewSubPath

func (c *Context) NewSubPath()

NewSubPath starts a new subpath without closing the previous one.

func (*Context) Pop

func (c *Context) Pop()

Pop restores the last saved state.

func (*Context) Push

func (c *Context) Push()

Push saves the current state (transform and paint).

func (*Context) QuadraticTo

func (c *Context) QuadraticTo(cx, cy, x, y float64)

QuadraticTo adds a quadratic Bezier curve to the current path.

func (*Context) Rotate

func (c *Context) Rotate(angle float64)

Rotate applies a rotation (angle in radians).

func (*Context) RotateAbout

func (c *Context) RotateAbout(angle, x, y float64)

RotateAbout rotates around a specific point.

func (*Context) SavePNG

func (c *Context) SavePNG(path string) error

SavePNG saves the context to a PNG file.

func (*Context) Scale

func (c *Context) Scale(x, y float64)

Scale applies a scaling transformation.

func (*Context) SetColor

func (c *Context) SetColor(col color.Color)

SetColor sets the current drawing color.

func (*Context) SetFillRule

func (c *Context) SetFillRule(rule FillRule)

SetFillRule sets the fill rule.

func (*Context) SetHexColor

func (c *Context) SetHexColor(hex string)

SetHexColor sets the current color using a hex string.

func (*Context) SetLineCap

func (c *Context) SetLineCap(lineCap LineCap)

SetLineCap sets the line cap style.

func (*Context) SetLineJoin

func (c *Context) SetLineJoin(join LineJoin)

SetLineJoin sets the line join style.

func (*Context) SetLineWidth

func (c *Context) SetLineWidth(width float64)

SetLineWidth sets the line width for stroking.

func (*Context) SetPixel

func (c *Context) SetPixel(x, y int, col RGBA)

SetPixel sets a single pixel.

func (*Context) SetRGB

func (c *Context) SetRGB(r, g, b float64)

SetRGB sets the current color using RGB values (0-1).

func (*Context) SetRGBA

func (c *Context) SetRGBA(r, g, b, a float64)

SetRGBA sets the current color using RGBA values (0-1).

func (*Context) Shear

func (c *Context) Shear(x, y float64)

Shear applies a shear transformation.

func (*Context) Stroke

func (c *Context) Stroke()

Stroke strokes the current path.

func (*Context) StrokePreserve

func (c *Context) StrokePreserve()

StrokePreserve strokes the current path and preserves it.

func (*Context) TransformPoint

func (c *Context) TransformPoint(x, y float64) (float64, float64)

TransformPoint transforms a point by the current matrix.

func (*Context) Translate

func (c *Context) Translate(x, y float64)

Translate applies a translation to the transformation matrix.

func (*Context) Width

func (c *Context) Width() int

Width returns the width of the context.

type CubicTo

type CubicTo struct {
	Control1 Point
	Control2 Point
	Point    Point
}

CubicTo draws a cubic Bezier curve.

type FillRule

type FillRule int

FillRule specifies how to determine which areas are inside a path.

const (
	// FillRuleNonZero uses the non-zero winding rule.
	FillRuleNonZero FillRule = iota
	// FillRuleEvenOdd uses the even-odd rule.
	FillRuleEvenOdd
)

type LineCap

type LineCap int

LineCap specifies the shape of line endpoints.

const (
	// LineCapButt specifies a flat line cap.
	LineCapButt LineCap = iota
	// LineCapRound specifies a rounded line cap.
	LineCapRound
	// LineCapSquare specifies a square line cap.
	LineCapSquare
)

type LineJoin

type LineJoin int

LineJoin specifies the shape of line joins.

const (
	// LineJoinMiter specifies a sharp (mitered) join.
	LineJoinMiter LineJoin = iota
	// LineJoinRound specifies a rounded join.
	LineJoinRound
	// LineJoinBevel specifies a beveled join.
	LineJoinBevel
)

type LineTo

type LineTo struct {
	Point Point
}

LineTo draws a line to a point.

type Matrix

type Matrix struct {
	A, B, C float64
	D, E, F float64
}

Matrix represents a 2D affine transformation matrix. It uses a 2x3 matrix in row-major order:

| a  b  c |
| d  e  f |

This represents the transformation:

x' = a*x + b*y + c
y' = d*x + e*y + f

func Identity

func Identity() Matrix

Identity returns the identity transformation matrix.

func Rotate

func Rotate(angle float64) Matrix

Rotate creates a rotation matrix (angle in radians).

func Scale

func Scale(x, y float64) Matrix

Scale creates a scaling matrix.

func Shear

func Shear(x, y float64) Matrix

Shear creates a shear matrix.

func Translate

func Translate(x, y float64) Matrix

Translate creates a translation matrix.

func (Matrix) Invert

func (m Matrix) Invert() Matrix

Invert returns the inverse matrix. Returns the identity matrix if the matrix is not invertible.

func (Matrix) IsIdentity

func (m Matrix) IsIdentity() bool

IsIdentity returns true if the matrix is the identity matrix.

func (Matrix) IsTranslation

func (m Matrix) IsTranslation() bool

IsTranslation returns true if the matrix is only a translation.

func (Matrix) Multiply

func (m Matrix) Multiply(other Matrix) Matrix

Multiply multiplies two matrices (m * other).

func (Matrix) TransformPoint

func (m Matrix) TransformPoint(p Point) Point

TransformPoint applies the transformation to a point.

func (Matrix) TransformVector

func (m Matrix) TransformVector(p Point) Point

TransformVector applies the transformation to a vector (no translation).

type MoveTo

type MoveTo struct {
	Point Point
}

MoveTo moves to a point without drawing.

type Paint

type Paint struct {
	// Pattern is the fill or stroke pattern
	Pattern Pattern

	// LineWidth is the width of strokes
	LineWidth float64

	// LineCap is the shape of line endpoints
	LineCap LineCap

	// LineJoin is the shape of line joins
	LineJoin LineJoin

	// MiterLimit is the miter limit for sharp joins
	MiterLimit float64

	// FillRule is the fill rule for paths
	FillRule FillRule

	// Antialias enables anti-aliasing
	Antialias bool
}

Paint represents the styling information for drawing.

func NewPaint

func NewPaint() *Paint

NewPaint creates a new Paint with default values.

func (*Paint) Clone

func (p *Paint) Clone() *Paint

Clone creates a copy of the Paint.

type Path

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

Path represents a vector path.

func NewPath

func NewPath() *Path

NewPath creates a new empty path.

func (*Path) Arc

func (p *Path) Arc(cx, cy, r, angle1, angle2 float64)

Arc adds a circular arc to the path. The arc is drawn from angle1 to angle2 (in radians) around center (cx, cy).

func (*Path) Circle

func (p *Path) Circle(cx, cy, r float64)

Circle adds a circle to the path using cubic Bezier curves.

func (*Path) Clear

func (p *Path) Clear()

Clear removes all elements from the path.

func (*Path) Close

func (p *Path) Close()

Close closes the current subpath by drawing a line to the start point.

func (*Path) CubicTo

func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float64)

CubicTo draws a cubic Bezier curve.

func (*Path) CurrentPoint

func (p *Path) CurrentPoint() Point

CurrentPoint returns the current point.

func (*Path) Elements

func (p *Path) Elements() []PathElement

Elements returns the path elements.

func (*Path) Ellipse

func (p *Path) Ellipse(cx, cy, rx, ry float64)

Ellipse adds an ellipse to the path.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64)

LineTo draws a line to a point.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64)

MoveTo moves to a point without drawing.

func (*Path) QuadraticTo

func (p *Path) QuadraticTo(cx, cy, x, y float64)

QuadraticTo draws a quadratic Bezier curve.

func (*Path) Rectangle

func (p *Path) Rectangle(x, y, w, h float64)

Rectangle adds a rectangle to the path.

func (*Path) RoundedRectangle

func (p *Path) RoundedRectangle(x, y, w, h, r float64)

RoundedRectangle adds a rectangle with rounded corners.

func (*Path) Transform

func (p *Path) Transform(m Matrix) *Path

Transform applies a transformation matrix to all points in the path.

type PathElement

type PathElement interface {
	// contains filtered or unexported methods
}

PathElement represents a single element in a path.

type Pattern

type Pattern interface {
	// ColorAt returns the color at the given point.
	ColorAt(x, y float64) RGBA
}

Pattern represents a fill or stroke pattern.

type Pixmap

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

Pixmap represents a rectangular pixel buffer.

func FromImage

func FromImage(img image.Image) *Pixmap

FromImage creates a pixmap from an image.

func NewPixmap

func NewPixmap(width, height int) *Pixmap

NewPixmap creates a new pixmap with the given dimensions.

func (*Pixmap) At

func (p *Pixmap) At(x, y int) color.Color

At implements the image.Image interface.

func (*Pixmap) Bounds

func (p *Pixmap) Bounds() image.Rectangle

Bounds implements the image.Image interface.

func (*Pixmap) Clear

func (p *Pixmap) Clear(c RGBA)

Clear fills the entire pixmap with a color.

func (*Pixmap) ColorModel

func (p *Pixmap) ColorModel() color.Model

ColorModel implements the image.Image interface.

func (*Pixmap) Data

func (p *Pixmap) Data() []uint8

Data returns the raw pixel data (RGBA format).

func (*Pixmap) GetPixel

func (p *Pixmap) GetPixel(x, y int) RGBA

GetPixel returns the color of a single pixel.

func (*Pixmap) Height

func (p *Pixmap) Height() int

Height returns the height of the pixmap.

func (*Pixmap) SavePNG

func (p *Pixmap) SavePNG(path string) error

SavePNG saves the pixmap to a PNG file.

func (*Pixmap) SetPixel

func (p *Pixmap) SetPixel(x, y int, c RGBA)

SetPixel sets the color of a single pixel.

func (*Pixmap) ToImage

func (p *Pixmap) ToImage() *image.RGBA

ToImage converts the pixmap to an image.RGBA.

func (*Pixmap) Width

func (p *Pixmap) Width() int

Width returns the width of the pixmap.

type Point

type Point struct {
	X, Y float64
}

Point represents a 2D point or vector.

func Pt

func Pt(x, y float64) Point

Pt is a convenience function to create a Point.

func (Point) Add

func (p Point) Add(q Point) Point

Add returns the sum of two points (vector addition).

func (Point) Cross

func (p Point) Cross(q Point) float64

Cross returns the 2D cross product (scalar).

func (Point) Distance

func (p Point) Distance(q Point) float64

Distance returns the distance between two points.

func (Point) Div

func (p Point) Div(s float64) Point

Div returns the point divided by a scalar.

func (Point) Dot

func (p Point) Dot(q Point) float64

Dot returns the dot product of two vectors.

func (Point) Length

func (p Point) Length() float64

Length returns the length of the vector.

func (Point) LengthSquared

func (p Point) LengthSquared() float64

LengthSquared returns the squared length of the vector.

func (Point) Lerp

func (p Point) Lerp(q Point, t float64) Point

Lerp performs linear interpolation between two points. t=0 returns p, t=1 returns q, intermediate values interpolate.

func (Point) Mul

func (p Point) Mul(s float64) Point

Mul returns the point scaled by a scalar.

func (Point) Normalize

func (p Point) Normalize() Point

Normalize returns a unit vector in the same direction.

func (Point) Rotate

func (p Point) Rotate(angle float64) Point

Rotate returns the point rotated by angle radians around the origin.

func (Point) Sub

func (p Point) Sub(q Point) Point

Sub returns the difference of two points (vector subtraction).

type QuadTo

type QuadTo struct {
	Control Point
	Point   Point
}

QuadTo draws a quadratic Bezier curve.

type RGBA

type RGBA struct {
	R, G, B, A float64
}

RGBA represents a color with red, green, blue, and alpha components. Each component is in the range [0, 1].

func FromColor

func FromColor(c color.Color) RGBA

FromColor converts a standard color.Color to RGBA.

func HSL

func HSL(h, s, l float64) RGBA

HSL creates a color from HSL values. h is hue [0, 360), s is saturation [0, 1], l is lightness [0, 1].

func Hex

func Hex(hex string) RGBA

Hex creates a color from a hex string. Supports formats: "RGB", "RGBA", "RRGGBB", "RRGGBBAA".

func RGB

func RGB(r, g, b float64) RGBA

RGB creates an opaque color from RGB components.

func RGBA2

func RGBA2(r, g, b, a float64) RGBA

RGBA2 creates a color from RGBA components.

func (RGBA) Color

func (c RGBA) Color() color.Color

Color converts RGBA to the standard color.Color interface.

func (RGBA) Lerp

func (c RGBA) Lerp(other RGBA, t float64) RGBA

Lerp performs linear interpolation between two colors.

func (RGBA) Premultiply

func (c RGBA) Premultiply() RGBA

Premultiply returns a premultiplied color.

func (RGBA) Unpremultiply

func (c RGBA) Unpremultiply() RGBA

Unpremultiply returns an unpremultiplied color.

type Renderer

type Renderer interface {
	// Fill fills a path with the given paint.
	Fill(pixmap *Pixmap, path *Path, paint *Paint)

	// Stroke strokes a path with the given paint.
	Stroke(pixmap *Pixmap, path *Path, paint *Paint)
}

Renderer is the interface for rendering paths to a pixmap.

type SoftwareRenderer

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

SoftwareRenderer is a CPU-based scanline rasterizer.

func NewSoftwareRenderer

func NewSoftwareRenderer(width, height int) *SoftwareRenderer

NewSoftwareRenderer creates a new software renderer.

func (*SoftwareRenderer) Fill

func (r *SoftwareRenderer) Fill(pixmap *Pixmap, p *Path, paint *Paint)

Fill implements Renderer.Fill.

func (*SoftwareRenderer) Stroke

func (r *SoftwareRenderer) Stroke(pixmap *Pixmap, p *Path, paint *Paint)

Stroke implements Renderer.Stroke.

type SolidPattern

type SolidPattern struct {
	Color RGBA
}

SolidPattern represents a solid color pattern.

func NewSolidPattern

func NewSolidPattern(color RGBA) *SolidPattern

NewSolidPattern creates a solid color pattern.

func (*SolidPattern) ColorAt

func (p *SolidPattern) ColorAt(x, y float64) RGBA

ColorAt implements Pattern.

Directories

Path Synopsis
cmd
ggdemo command
Command ggdemo demonstrates the gg 2D graphics library.
Command ggdemo demonstrates the gg 2D graphics library.
examples
basic command
shapes command
text command
internal
blend
Package blend provides color blending operations.
Package blend provides color blending operations.
path
Package path provides internal path processing utilities.
Package path provides internal path processing utilities.
raster
Package raster provides scanline rasterization for 2D paths.
Package raster provides scanline rasterization for 2D paths.

Jump to

Keyboard shortcuts

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