gg

package module
v0.15.7 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 15 Imported by: 0

README

gg

Enterprise-Grade 2D Graphics Library for Go
Pure Go | GPU Accelerated | Rust-Inspired Architecture

CI codecov Go Reference Go Report Card License Latest Release Stars Discussions

Go 1.25+ Required


Overview

gg is a professional 2D graphics library for Go, designed to power IDEs, browsers, and graphics-intensive applications. Built with modern Rust-inspired patterns from vello and tiny-skia, it delivers enterprise-grade rendering with zero CGO dependencies.

Key Features

Category Capabilities
Rendering Immediate & retained mode, GPU acceleration via WebGPU, CPU fallback
Shapes Rectangles, circles, ellipses, arcs, bezier curves, polygons, stars
Text TrueType fonts, MSDF rendering, emoji/COLRv1, bidirectional text, CJK
Compositing 29 blend modes (Porter-Duff + Advanced + HSL), layer isolation
Images 7 pixel formats, PNG/JPEG I/O, mipmaps, affine transforms
Performance Sparse strips GPU, tile-based parallel rendering, LRU caching

Architecture Highlights

                         gg (Public API)
                              │
          ┌───────────────────┼───────────────────┐
          │                   │                   │
    Immediate Mode       Retained Mode        Resources
    (Context API)        (Scene Graph)     (Images, Fonts)
          │                   │                   │
          └───────────────────┼───────────────────┘
                              │
                     RenderBackend Interface
                              │
             ┌────────────────┼────────────────┐
             │                                 │
        Software                             GPU
        (CPU SIMD)                    (gogpu/wgpu WebGPU)

Why "Context" Instead of "Canvas"?

The main drawing type is named Context following industry standards:

Library Drawing Type
HTML5 Canvas API CanvasRenderingContext2D
Cairo cairo_t (context)
Apple CoreGraphics CGContext
piet (Rust) RenderContext
fogleman/gg Context

In HTML5, the Canvas is just the HTML element (surface), while the Context is what performs all drawing operations (canvas.getContext("2d")). This semantic distinction applies here: Context contains drawing state (colors, transforms, fonts) and provides the drawing API.

Variable naming convention:

dc := gg.NewContext(512, 512)  // dc = drawing context

This convention (dc for drawing, ctx for context.Context) avoids confusion with Go's standard library and is used throughout fogleman/gg, Cairo, and CoreGraphics codebases.


Installation

go get github.com/gogpu/gg

Quick Start

package main

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

func main() {
    // Create a 512x512 drawing context
    dc := gg.NewContext(512, 512)
    defer dc.Close() // Clean resource release

    dc.ClearWithColor(gg.White)

    // Draw a gradient circle
    dc.SetHexColor("#3498db")
    dc.DrawCircle(256, 256, 100)
    dc.Fill()

    // Text rendering with font fallback
    source, _ := text.NewFontSourceFromFile("arial.ttf")
    defer source.Close()

    dc.SetFont(source.Face(32))
    dc.SetColor(gg.Black)
    dc.DrawString("Hello, GoGPU!", 180, 260)

    dc.SavePNG("output.png")
}

Core APIs

Immediate Mode (Context)

Classic canvas-style drawing with transformation stack:

dc := gg.NewContext(800, 600)
defer dc.Close()

// Shapes with transforms
dc.Push()
dc.Translate(400, 300)
dc.Rotate(math.Pi / 4)
dc.DrawRectangle(-50, -50, 100, 100)
dc.SetRGB(0.2, 0.5, 0.8)
dc.Fill()
dc.Pop()

// Bezier paths
dc.MoveTo(100, 100)
dc.QuadraticTo(200, 50, 300, 100)
dc.CubicTo(350, 150, 350, 250, 300, 300)
dc.SetLineWidth(3)
dc.Stroke()

Fluent Path Builder

Type-safe path construction with method chaining:

path := gg.BuildPath().
    MoveTo(100, 100).
    LineTo(200, 100).
    QuadTo(250, 150, 200, 200).
    CubicTo(150, 250, 100, 250, 50, 200).
    Close().
    Circle(300, 150, 50).
    Star(400, 150, 40, 20, 5).
    Build()

dc.SetPath(path)
dc.Fill()

Retained Mode (Scene Graph)

GPU-optimized scene graph for complex applications:

scene := gg.NewScene()

// Build scene with layers
scene.PushLayer(gg.BlendMultiply, 0.8)
scene.Fill(style, transform, gg.Solid(gg.Red), gg.Circle(150, 200, 100))
scene.Fill(style, transform, gg.Solid(gg.Blue), gg.Circle(250, 200, 100))
scene.PopLayer()

// Render to pixmap
renderer := scene.NewRenderer()
renderer.Render(target, scene)

Text Rendering

Full Unicode support with bidirectional text:

// Font composition with fallback
mainFont, _ := text.NewFontSourceFromFile("Roboto.ttf")
emojiFont, _ := text.NewFontSourceFromFile("NotoEmoji.ttf")
defer mainFont.Close()
defer emojiFont.Close()

multiFace, _ := text.NewMultiFace(
    mainFont.Face(24),
    text.NewFilteredFace(emojiFont.Face(24), text.RangeEmoji),
)

dc.SetFont(multiFace)
dc.DrawString("Hello World! Nice day!", 50, 100)

// Layout with wrapping
opts := text.LayoutOptions{
    MaxWidth: 400,
    WrapMode: text.WrapWordChar,
    Alignment: text.AlignCenter,
}
layout := text.LayoutText("Long text...", face, 16, opts)

Alpha Masks

Sophisticated compositing with alpha masks:

// Create mask from current drawing
dc.DrawCircle(200, 200, 100)
dc.Fill()
mask := dc.AsMask()

// Apply mask to new context
dc2 := gg.NewContext(400, 400)
dc2.SetMask(mask)
dc2.DrawRectangle(0, 0, 400, 400)
dc2.Fill() // Only visible through mask

// Mask operations
dc2.InvertMask()
dc2.ClearMask()

Layer Compositing

29 blend modes with isolated layers:

dc.PushLayer(gg.BlendOverlay, 0.7)

dc.SetRGB(1, 0, 0)
dc.DrawCircle(150, 200, 100)
dc.Fill()

dc.SetRGB(0, 0, 1)
dc.DrawCircle(250, 200, 100)
dc.Fill()

dc.PopLayer() // Composite with overlay blend

Ecosystem

gg is part of the GoGPU ecosystem — Pure Go GPU computing libraries.

Project Description Purpose
gogpu/gogpu Graphics framework GPU abstraction, windowing, input
gogpu/wgpu Pure Go WebGPU Vulkan, Metal, GLES, Software backends
gogpu/naga Shader compiler WGSL → SPIR-V, MSL, GLSL
gogpu/gg 2D graphics (this repo) Canvas API, scene graph, GPU text
gogpu/ui GUI toolkit Widgets, layouts, themes (planned)

Note: Always use the latest versions. Check each repository for current releases.


Performance

Operation Time Notes
sRGB → Linear 0.16ns 260x faster than math.Pow
LayerCache.Get 90ns Thread-safe LRU
DirtyRegion.Mark 10.9ns Lock-free atomic
MSDF lookup <10ns Zero-allocation
Path iteration 438ns iter.Seq, 0 allocs

Documentation


Articles


Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

Priority areas:

  • API feedback and testing
  • Examples and documentation
  • Performance benchmarks
  • Cross-platform testing

License

MIT License — see LICENSE for details.

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 drawing context (dc = drawing context convention)
dc := gg.NewContext(512, 512)

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

// Save to PNG
dc.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

The library includes both software and GPU-accelerated renderers:

  • Software rasterizer for broad compatibility
  • GPU renderer via gogpu/wgpu for high performance

Architecture

The library is organized into:

  • Public API: Context, Path, Paint, Matrix, Point
  • Internal: raster (scanline), path (tessellation), blend (compositing)
  • Renderers: software, gpu (wgpu)

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 prioritizes correctness. For performance-critical applications, use the GPU renderer.

Index

Constants

View Source
const (
	// InterpNearest selects the closest pixel (no interpolation).
	// Fast but produces blocky results when scaling.
	InterpNearest = intImage.InterpNearest

	// InterpBilinear performs linear interpolation between 4 neighboring pixels.
	// Good balance between quality and performance.
	InterpBilinear = intImage.InterpBilinear

	// InterpBicubic performs cubic interpolation using a 4x4 pixel neighborhood.
	// Highest quality but slower than bilinear.
	InterpBicubic = intImage.InterpBicubic
)

Image interpolation modes.

View Source
const (
	// FormatGray8 is 8-bit grayscale (1 byte per pixel).
	FormatGray8 = intImage.FormatGray8

	// FormatGray16 is 16-bit grayscale (2 bytes per pixel).
	FormatGray16 = intImage.FormatGray16

	// FormatRGB8 is 24-bit RGB (3 bytes per pixel, no alpha).
	FormatRGB8 = intImage.FormatRGB8

	// FormatRGBA8 is 32-bit RGBA in sRGB color space (4 bytes per pixel).
	// This is the standard format for most operations.
	FormatRGBA8 = intImage.FormatRGBA8

	// FormatRGBAPremul is 32-bit RGBA with premultiplied alpha (4 bytes per pixel).
	// Used for correct alpha blending operations.
	FormatRGBAPremul = intImage.FormatRGBAPremul

	// FormatBGRA8 is 32-bit BGRA in sRGB color space (4 bytes per pixel).
	// Common on Windows and some GPU formats.
	FormatBGRA8 = intImage.FormatBGRA8

	// FormatBGRAPremul is 32-bit BGRA with premultiplied alpha (4 bytes per pixel).
	FormatBGRAPremul = intImage.FormatBGRAPremul
)

Pixel formats.

View Source
const (
	// BlendNormal performs standard alpha blending (source over destination).
	BlendNormal = intImage.BlendNormal

	// BlendMultiply multiplies source and destination colors.
	// Result is always darker or equal. Formula: dst * src
	BlendMultiply = intImage.BlendMultiply

	// BlendScreen performs inverse multiply for lighter results.
	// Formula: 1 - (1-dst) * (1-src)
	BlendScreen = intImage.BlendScreen

	// BlendOverlay combines multiply and screen based on destination brightness.
	// Dark areas are multiplied, bright areas are screened.
	BlendOverlay = intImage.BlendOverlay
)

Blend modes.

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

func SolveCubic added in v0.9.1

func SolveCubic(a, b, c, d float64) []float64

SolveCubic finds real roots of the cubic equation ax^3 + bx^2 + cx + d = 0. Returns roots (not necessarily sorted).

The implementation uses the method from: https://momentsingraphics.de/CubicRoots.html which is based on Jim Blinn's "How to Solve a Cubic Equation".

func SolveCubicInUnitInterval added in v0.9.1

func SolveCubicInUnitInterval(a, b, c, d float64) []float64

SolveCubicInUnitInterval returns roots of ax^3 + bx^2 + cx + d = 0 that lie in [0, 1]. This is useful for finding parameter values on Bezier curves.

func SolveQuadratic added in v0.9.1

func SolveQuadratic(a, b, c float64) []float64

SolveQuadratic finds real roots of the quadratic equation ax^2 + bx + c = 0. Returns roots sorted in ascending order.

The function is numerically robust: - If a is zero or nearly zero, treats as linear equation - If all coefficients are zero, returns a single 0.0 - Handles edge cases with NaN and Inf gracefully

func SolveQuadraticInUnitInterval added in v0.9.1

func SolveQuadraticInUnitInterval(a, b, c float64) []float64

SolveQuadraticInUnitInterval returns roots of ax^2 + bx + c = 0 that lie in [0, 1]. This is useful for finding parameter values on Bezier curves.

Types

type BlendMode added in v0.3.0

type BlendMode = intImage.BlendMode

BlendMode defines how source pixels are blended with destination pixels.

type Brush added in v0.12.0

type Brush interface {

	// ColorAt returns the color at the given coordinates.
	// For solid brushes, this returns the same color regardless of position.
	// For pattern-based brushes, this samples the pattern at (x, y).
	ColorAt(x, y float64) RGBA
	// contains filtered or unexported methods
}

Brush represents what to paint with. This is a sealed interface - only types in this package implement it.

The Brush pattern follows vello/peniko Rust conventions, providing a type-safe way to represent different brush types (solid colors, gradients, images) while maintaining extensibility through CustomBrush.

Supported brush types:

  • SolidBrush: A single solid color
  • CustomBrush: User-defined color function (see brush_custom.go)

Example usage:

// Using convenience constructors
ctx.SetFillBrush(gg.Solid(gg.Red))
ctx.SetStrokeBrush(gg.SolidRGB(0.5, 0.5, 0.5))

// Using hex colors
brush := gg.SolidHex("#FF5733")

func BrushFromPattern deprecated added in v0.12.0

func BrushFromPattern(p Pattern) Brush

BrushFromPattern converts a legacy Pattern to a Brush. This is a compatibility helper for migrating from Pattern to Brush.

If the pattern is a SolidPattern, it returns a SolidBrush. Otherwise, it wraps the pattern in a CustomBrush.

Deprecated: Use Brush types directly instead of Pattern.

type Close

type Close struct{}

Close closes the current subpath.

type ColorFunc added in v0.12.0

type ColorFunc func(x, y float64) RGBA

ColorFunc is a function that returns a color at a given position. Used by CustomBrush to define custom brush patterns.

type ColorStop added in v0.12.0

type ColorStop struct {
	Offset float64 // Position in gradient, 0.0 to 1.0
	Color  RGBA    // Color at this position
}

ColorStop represents a color at a specific position in a gradient.

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. Context implements io.Closer for proper resource cleanup.

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) AsMask added in v0.14.0

func (c *Context) AsMask() *Mask

AsMask creates a mask from the current path. The mask is filled according to the current fill rule. The path is NOT cleared after this operation.

func (*Context) Clear

func (c *Context) Clear()

Clear fills the entire context with a color.

func (*Context) ClearDash added in v0.12.0

func (c *Context) ClearDash()

ClearDash removes the dash pattern, returning to solid lines.

func (*Context) ClearMask added in v0.14.0

func (c *Context) ClearMask()

ClearMask removes the current mask.

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) Clip added in v0.3.0

func (c *Context) Clip()

Clip sets the current path as the clipping region and clears the path. Subsequent drawing operations will be clipped to this region. The clip region is intersected with any existing clip regions.

func (*Context) ClipPreserve added in v0.3.0

func (c *Context) ClipPreserve()

ClipPreserve sets the current path as the clipping region but keeps the path. This is like Clip() but doesn't clear the path, allowing you to both clip and then fill/stroke the same path.

func (*Context) ClipRect added in v0.3.0

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

ClipRect sets a rectangular clipping region. This is a faster alternative to creating a rectangular path and calling Clip(). The clip region is intersected with any existing clip regions.

func (*Context) Close added in v0.14.0

func (c *Context) Close() error

Close releases resources associated with the Context. After Close, the Context should not be used. Close is idempotent - multiple calls are safe. Implements io.Closer.

func (*Context) ClosePath

func (c *Context) ClosePath()

ClosePath closes the current subpath.

func (*Context) CreateImagePattern added in v0.3.0

func (c *Context) CreateImagePattern(img *ImageBuf, x, y, w, h int) Pattern

CreateImagePattern creates an image pattern from a rectangular region of an image. The pattern can be used with SetFillPattern or SetStrokePattern.

Example:

img, _ := gg.LoadImage("texture.png")
pattern := dc.CreateImagePattern(img, 0, 0, 100, 100)
dc.SetFillPattern(pattern)
dc.DrawRectangle(0, 0, 400, 300)
dc.Fill()

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) DrawImage added in v0.3.0

func (c *Context) DrawImage(img *ImageBuf, x, y float64)

DrawImage draws an image at the specified position. The current transformation matrix is applied to the position and size.

Example:

img, _ := gg.LoadImage("photo.png")
dc.DrawImage(img, 100, 100)

func (*Context) DrawImageEx added in v0.3.0

func (c *Context) DrawImageEx(img *ImageBuf, opts DrawImageOptions)

DrawImageEx draws an image with advanced options. The current transformation matrix is applied to the position and size.

Example:

dc.DrawImageEx(img, gg.DrawImageOptions{
    X:             100,
    Y:             100,
    DstWidth:      200,
    DstHeight:     150,
    Interpolation: gg.InterpBicubic,
    Opacity:       0.8,
    BlendMode:     gg.BlendNormal,
})

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 draws text at position (x, y) where y is the baseline. If no font has been set with SetFont, this function does nothing.

The baseline is the line on which most letters sit. Characters with descenders (like 'g', 'j', 'p', 'q', 'y') extend below the baseline.

func (*Context) DrawStringAnchored

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

DrawStringAnchored draws text with an anchor point. The anchor point is specified by ax and ay, which are in the range [0, 1].

(0, 0) = top-left
(0.5, 0.5) = center
(1, 1) = bottom-right

The text is positioned so that the anchor point is at (x, y).

func (*Context) EncodeJPEG added in v0.14.0

func (c *Context) EncodeJPEG(w io.Writer, quality int) error

EncodeJPEG writes the image as JPEG with the given quality (1-100).

func (*Context) EncodePNG added in v0.14.0

func (c *Context) EncodePNG(w io.Writer) error

EncodePNG writes the image as PNG to the given writer. This is useful for streaming, network output, or custom storage.

func (*Context) Fill

func (c *Context) Fill()

Fill fills the current path.

func (*Context) FillBrush added in v0.12.0

func (c *Context) FillBrush() Brush

FillBrush returns the current fill brush.

func (*Context) FillPreserve

func (c *Context) FillPreserve()

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

func (*Context) Font added in v0.2.0

func (c *Context) Font() text.Face

Font returns the current font face. Returns nil if no font has been set.

func (*Context) GetCurrentPoint added in v0.14.0

func (c *Context) GetCurrentPoint() (x, y float64, ok bool)

GetCurrentPoint returns the current point of the path. Returns (0, 0, false) if there is no current point.

func (*Context) GetMask added in v0.14.0

func (c *Context) GetMask() *Mask

GetMask returns the current mask, or nil if no mask is set.

func (*Context) GetStroke added in v0.12.0

func (c *Context) GetStroke() Stroke

GetStroke returns the current stroke style.

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) InvertMask added in v0.14.0

func (c *Context) InvertMask()

InvertMask inverts the current mask. Has no effect if no mask is set.

func (*Context) InvertY

func (c *Context) InvertY()

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

func (*Context) IsDashed added in v0.12.0

func (c *Context) IsDashed() bool

IsDashed returns true if the current stroke uses a dash pattern.

func (*Context) LineTo

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

LineTo adds a line to the current path.

func (*Context) LoadFontFace deprecated

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

LoadFontFace loads a font from a file and sets it as the current font. The size is specified in points.

Deprecated: Use text.NewFontSourceFromFile and SetFont instead. This method is provided for convenience and backward compatibility.

Example (new way):

source, err := text.NewFontSourceFromFile("font.ttf")
if err != nil {
    return err
}
face := source.Face(12.0)
ctx.SetFont(face)

func (*Context) MeasureString

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

MeasureString returns the dimensions of text in pixels. Returns (width, height) where:

  • width is the horizontal advance of the text
  • height is the line height (ascent + descent + line gap)

If no font has been set, returns (0, 0).

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) PopLayer added in v0.4.0

func (c *Context) PopLayer()

PopLayer composites the current layer onto the parent layer/canvas. Uses the blend mode and opacity specified in the corresponding PushLayer call.

The layer is composited using the specified blend mode and opacity. After compositing, the layer's memory is returned to the pool for reuse.

If there are no layers to pop, this function does nothing.

Example:

dc.PushLayer(gg.BlendScreen, 1.0)
// ... draw operations ...
dc.PopLayer() // Composite layer onto parent

func (*Context) Push

func (c *Context) Push()

Push saves the current state (transform, paint, clip, and mask).

func (*Context) PushLayer added in v0.4.0

func (c *Context) PushLayer(blendMode BlendMode, opacity float64)

PushLayer creates a new layer and makes it the active drawing target. All subsequent drawing operations will render to this layer until PopLayer is called.

The layer will be composited onto the parent layer/canvas when PopLayer is called, using the specified blend mode and opacity.

Parameters:

  • blendMode: How to composite this layer onto the parent (e.g., BlendMultiply, BlendScreen)
  • opacity: Layer opacity in range [0.0, 1.0] where 0 is fully transparent and 1 is fully opaque

Example:

dc.PushLayer(gg.BlendMultiply, 0.5)
dc.SetRGB(1, 0, 0)
dc.DrawCircle(100, 100, 50)
dc.Fill()
dc.PopLayer() // Composite circle onto canvas with multiply blend at 50% opacity

func (*Context) QuadraticTo

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

QuadraticTo adds a quadratic Bezier curve to the current path.

func (*Context) ResetClip added in v0.3.0

func (c *Context) ResetClip()

ResetClip removes all clipping regions, restoring the full canvas as drawable.

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) SetBlendMode added in v0.4.0

func (c *Context) SetBlendMode(_ BlendMode)

SetBlendMode sets the blend mode for subsequent fill and stroke operations. This is currently a placeholder for future blend mode support in direct drawing operations.

For now, blend modes are primarily used with layers via PushLayer/PopLayer.

Example:

dc.SetBlendMode(gg.BlendMultiply)
dc.Fill() // Future: will use multiply blend mode

func (*Context) SetColor

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

SetColor sets the current drawing color.

func (*Context) SetDash added in v0.12.0

func (c *Context) SetDash(lengths ...float64)

SetDash sets the dash pattern for stroking. Pass alternating dash and gap lengths. Passing no arguments clears the dash pattern (returns to solid lines).

Example:

ctx.SetDash(5, 3)       // 5 units dash, 3 units gap
ctx.SetDash(10, 5, 2, 5) // complex pattern
ctx.SetDash()           // clear dash (solid line)

func (*Context) SetDashOffset added in v0.12.0

func (c *Context) SetDashOffset(offset float64)

SetDashOffset sets the starting offset into the dash pattern. This has no effect if no dash pattern is set.

func (*Context) SetFillBrush added in v0.12.0

func (c *Context) SetFillBrush(b Brush)

SetFillBrush sets the brush used for fill operations. This is the preferred way to set fill styling in new code.

Example:

ctx.SetFillBrush(gg.Solid(gg.Red))
ctx.SetFillBrush(gg.SolidHex("#FF5733"))
ctx.SetFillBrush(gg.HorizontalGradient(gg.Red, gg.Blue, 0, 100))

func (*Context) SetFillPattern added in v0.3.0

func (c *Context) SetFillPattern(pattern Pattern)

SetFillPattern sets the fill pattern.

func (*Context) SetFillRule

func (c *Context) SetFillRule(rule FillRule)

SetFillRule sets the fill rule.

func (*Context) SetFont added in v0.2.0

func (c *Context) SetFont(face text.Face)

SetFont sets the current font face for text drawing. The face should be created from a FontSource.

Example:

source, _ := text.NewFontSourceFromFile("font.ttf")
face := source.Face(12.0)
ctx.SetFont(face)

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) SetMask added in v0.14.0

func (c *Context) SetMask(mask *Mask)

SetMask sets an alpha mask for subsequent drawing operations. The mask modulates the alpha of all drawing operations. Pass nil to clear the mask.

func (*Context) SetMiterLimit added in v0.12.0

func (c *Context) SetMiterLimit(limit float64)

SetMiterLimit sets the miter limit for line joins.

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) SetStroke added in v0.12.0

func (c *Context) SetStroke(stroke Stroke)

SetStroke sets the complete stroke style. This is the preferred way to configure stroke properties.

Example:

ctx.SetStroke(gg.DefaultStroke().WithWidth(2).WithCap(gg.LineCapRound))
ctx.SetStroke(gg.DashedStroke(5, 3))

func (*Context) SetStrokeBrush added in v0.12.0

func (c *Context) SetStrokeBrush(b Brush)

SetStrokeBrush sets the brush used for stroke operations. Note: In the current implementation, fill and stroke share the same brush. This method is provided for API symmetry and future extensibility.

Example:

ctx.SetStrokeBrush(gg.Solid(gg.Black))
ctx.SetStrokeBrush(gg.SolidRGB(0.5, 0.5, 0.5))

func (*Context) SetStrokePattern added in v0.3.0

func (c *Context) SetStrokePattern(pattern Pattern)

SetStrokePattern sets the stroke pattern.

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) StrokeBrush added in v0.12.0

func (c *Context) StrokeBrush() Brush

StrokeBrush returns the current stroke brush. Note: In the current implementation, fill and stroke share the same brush.

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 CubicBez added in v0.9.1

type CubicBez struct {
	P0, P1, P2, P3 Point
}

CubicBez represents a cubic Bezier curve with control points P0, P1, P2, P3. P0 is the start point, P1 and P2 are control points, P3 is the end point.

func NewCubicBez added in v0.9.1

func NewCubicBez(p0, p1, p2, p3 Point) CubicBez

NewCubicBez creates a new cubic Bezier curve.

func (CubicBez) BoundingBox added in v0.9.1

func (c CubicBez) BoundingBox() Rect

BoundingBox returns the tight axis-aligned bounding box of the curve.

func (CubicBez) Deriv added in v0.9.1

func (c CubicBez) Deriv() QuadBez

Deriv returns the derivative curve (a quadratic Bezier). The derivative gives the tangent direction at any point.

func (CubicBez) End added in v0.9.1

func (c CubicBez) End() Point

End returns the ending point of the curve.

func (CubicBez) Eval added in v0.9.1

func (c CubicBez) Eval(t float64) Point

Eval evaluates the curve at parameter t (0 to 1) using de Casteljau's algorithm.

func (CubicBez) Extrema added in v0.9.1

func (c CubicBez) Extrema() []float64

Extrema returns parameter values where the derivative is zero (extrema points). For a cubic Bezier, there can be up to 4 extrema (2 for x, 2 for y).

func (CubicBez) Inflections added in v0.9.1

func (c CubicBez) Inflections() []float64

Inflections returns the parameter values of inflection points. An inflection point is where the curvature changes sign. A cubic can have 0, 1, or 2 inflection points.

func (CubicBez) Normal added in v0.9.1

func (c CubicBez) Normal(t float64) Vec2

Normal returns the normal vector (perpendicular to tangent) at parameter t.

func (CubicBez) Start added in v0.9.1

func (c CubicBez) Start() Point

Start returns the starting point of the curve.

func (CubicBez) Subdivide added in v0.9.1

func (c CubicBez) Subdivide() (CubicBez, CubicBez)

Subdivide splits the curve at t=0.5 into two halves using de Casteljau.

func (CubicBez) Subsegment added in v0.9.1

func (c CubicBez) Subsegment(t0, t1 float64) CubicBez

Subsegment returns the portion of the curve from t0 to t1.

func (CubicBez) Tangent added in v0.9.1

func (c CubicBez) Tangent(t float64) Vec2

Tangent returns the tangent vector at parameter t.

type CubicTo

type CubicTo struct {
	Control1 Point
	Control2 Point
	Point    Point
}

CubicTo draws a cubic Bezier curve.

type CustomBrush added in v0.12.0

type CustomBrush struct {
	// Func is the color function that determines the color at each point.
	Func ColorFunc

	// Name is an optional identifier for debugging and logging.
	Name string
}

CustomBrush is a brush with a user-defined color function. It allows for arbitrary patterns, gradients, and procedural textures.

CustomBrush implements the Brush interface, making it compatible with all brush-based operations.

Example:

// Create a checkerboard pattern
checker := gg.NewCustomBrush(func(x, y float64) gg.RGBA {
    if (int(x/10)+int(y/10))%2 == 0 {
        return gg.Black
    }
    return gg.White
})

func Checkerboard added in v0.12.0

func Checkerboard(c0, c1 RGBA, size float64) CustomBrush

Checkerboard creates a checkerboard pattern brush. size is the size of each square in pixels.

Example:

checker := gg.Checkerboard(gg.Black, gg.White, 10)

func HorizontalGradient added in v0.12.0

func HorizontalGradient(c0, c1 RGBA, x0, x1 float64) CustomBrush

HorizontalGradient creates a linear gradient from left to right. x0 and x1 define the gradient range in pixel coordinates.

Example:

gradient := gg.HorizontalGradient(gg.Red, gg.Blue, 0, 100)

func LinearGradient added in v0.12.0

func LinearGradient(c0, c1 RGBA, x0, y0, x1, y1 float64) CustomBrush

LinearGradient creates a linear gradient along an arbitrary line. The gradient is defined from point (x0, y0) to point (x1, y1).

Example:

// Diagonal gradient from top-left to bottom-right
gradient := gg.LinearGradient(gg.Red, gg.Blue, 0, 0, 100, 100)

func NewCustomBrush added in v0.12.0

func NewCustomBrush(fn ColorFunc) CustomBrush

NewCustomBrush creates a CustomBrush from a color function.

Example:

// Horizontal gradient from red to blue
gradient := gg.NewCustomBrush(func(x, y float64) gg.RGBA {
    t := x / 100.0 // Assuming 100px width
    return gg.Red.Lerp(gg.Blue, t)
})

func RadialGradient added in v0.12.0

func RadialGradient(c0, c1 RGBA, cx, cy, r float64) CustomBrush

RadialGradient creates a radial gradient from center outward. The gradient is defined from the center (cx, cy) with radius r. c0 is the center color, c1 is the edge color.

Example:

// White center fading to black at radius 50
gradient := gg.RadialGradient(gg.White, gg.Black, 50, 50, 50)

func Stripes added in v0.12.0

func Stripes(c0, c1 RGBA, width, angle float64) CustomBrush

Stripes creates a striped pattern brush. width is the stripe width, angle is the rotation in radians.

Example:

// Vertical stripes
stripes := gg.Stripes(gg.Red, gg.White, 10, 0)

// Diagonal stripes (45 degrees)
diag := gg.Stripes(gg.Blue, gg.Yellow, 10, math.Pi/4)

func VerticalGradient added in v0.12.0

func VerticalGradient(c0, c1 RGBA, y0, y1 float64) CustomBrush

VerticalGradient creates a linear gradient from top to bottom. y0 and y1 define the gradient range in pixel coordinates.

Example:

gradient := gg.VerticalGradient(gg.White, gg.Black, 0, 100)

func (CustomBrush) ColorAt added in v0.12.0

func (b CustomBrush) ColorAt(x, y float64) RGBA

ColorAt implements Brush. Returns the color from the custom function.

func (CustomBrush) WithName added in v0.12.0

func (b CustomBrush) WithName(name string) CustomBrush

WithName returns a new CustomBrush with the specified name. Useful for debugging and logging.

Example:

brush := gg.NewCustomBrush(myFunc).WithName("myPattern")

type Dash added in v0.12.0

type Dash struct {
	// Array contains alternating dash/gap lengths.
	// If the array has an odd number of elements, it is logically duplicated
	// to create an even-length pattern (e.g., [5] becomes [5, 5]).
	Array []float64

	// Offset is the starting offset into the pattern.
	// The stroke begins at this point in the pattern cycle.
	Offset float64
}

Dash defines a dash pattern for stroking. A dash pattern consists of alternating dash and gap lengths. For example, [5, 3] creates a pattern of 5 units dash, 3 units gap.

func NewDash added in v0.12.0

func NewDash(lengths ...float64) *Dash

NewDash creates a dash pattern from alternating dash/gap lengths. If an odd number of elements is provided, the pattern is conceptually duplicated to create an even-length pattern.

Examples:

NewDash(5, 3)       // 5 units dash, 3 units gap
NewDash(10, 5, 2, 5) // 10 dash, 5 gap, 2 dash, 5 gap
NewDash(5)          // equivalent to [5, 5]

Returns nil if no lengths are provided or all lengths are zero.

func (*Dash) Clone added in v0.12.0

func (d *Dash) Clone() *Dash

Clone creates a deep copy of the Dash.

func (*Dash) IsDashed added in v0.12.0

func (d *Dash) IsDashed() bool

IsDashed returns true if this represents a dashed line (not solid). Returns false for nil Dash or empty/all-zero arrays.

func (*Dash) NormalizedOffset added in v0.12.0

func (d *Dash) NormalizedOffset() float64

NormalizedOffset returns the offset normalized to be within one pattern cycle. This is useful for calculating where in the pattern a stroke should begin.

func (*Dash) PatternLength added in v0.12.0

func (d *Dash) PatternLength() float64

PatternLength returns the total length of one complete pattern cycle. For odd-length arrays, this includes the duplicated pattern.

func (*Dash) WithOffset added in v0.12.0

func (d *Dash) WithOffset(offset float64) *Dash

WithOffset returns a new Dash with the given offset. The offset determines where in the pattern the stroke begins.

type DrawImageOptions added in v0.3.0

type DrawImageOptions struct {
	// X, Y specify the top-left corner where the image will be drawn.
	X, Y float64

	// DstWidth and DstHeight specify the dimensions to scale the image to.
	// If zero, the source dimensions are used (possibly from SrcRect).
	DstWidth  float64
	DstHeight float64

	// SrcRect defines the source rectangle to sample from.
	// If nil, the entire source image is used.
	SrcRect *image.Rectangle

	// Interpolation specifies the interpolation mode for sampling.
	// Default is InterpBilinear.
	Interpolation InterpolationMode

	// Opacity controls the overall transparency of the source image (0.0 to 1.0).
	// 1.0 means fully opaque, 0.0 means fully transparent.
	// Default is 1.0.
	Opacity float64

	// BlendMode specifies how to blend source and destination pixels.
	// Default is BlendNormal.
	BlendMode BlendMode
}

DrawImageOptions specifies parameters for drawing an image.

type ExtendMode added in v0.12.0

type ExtendMode int

ExtendMode defines how gradients extend beyond their defined bounds.

const (
	// ExtendPad extends edge colors beyond bounds (default behavior).
	ExtendPad ExtendMode = iota
	// ExtendRepeat repeats the gradient pattern.
	ExtendRepeat
	// ExtendReflect mirrors the gradient pattern.
	ExtendReflect
)

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 ImageBuf added in v0.3.0

type ImageBuf = intImage.ImageBuf

ImageBuf is a public alias for internal ImageBuf. It represents a memory-efficient image buffer with support for multiple pixel formats and lazy premultiplication.

func ImageBufFromImage added in v0.3.0

func ImageBufFromImage(img image.Image) *ImageBuf

ImageBufFromImage creates an ImageBuf from a standard image.Image.

func LoadImage added in v0.3.0

func LoadImage(path string) (*ImageBuf, error)

LoadImage loads an image from a file and returns an ImageBuf. Supported formats: PNG, JPEG, GIF.

func NewImageBuf added in v0.3.0

func NewImageBuf(width, height int, format ImageFormat) (*ImageBuf, error)

NewImageBuf creates a new image buffer with the given dimensions and format.

type ImageFormat added in v0.3.0

type ImageFormat = intImage.Format

ImageFormat represents a pixel storage format.

type ImagePattern added in v0.3.0

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

ImagePattern represents an image-based pattern.

func (*ImagePattern) ColorAt added in v0.3.0

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

ColorAt implements the Pattern interface. It samples the image at the given coordinates using wrapping/tiling behavior.

type InterpolationMode added in v0.3.0

type InterpolationMode = intImage.InterpolationMode

InterpolationMode defines how texture sampling is performed when drawing images.

type Layer added in v0.4.0

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

Layer represents a drawing layer with blend mode and opacity. Layers allow isolating drawing operations and compositing them with different blend modes and opacity values, similar to layers in Photoshop or SVG group opacity.

type Line added in v0.9.1

type Line struct {
	P0, P1 Point
}

Line represents a line segment from P0 to P1.

func NewLine added in v0.9.1

func NewLine(p0, p1 Point) Line

NewLine creates a new line segment.

func (Line) BoundingBox added in v0.9.1

func (l Line) BoundingBox() Rect

BoundingBox returns the axis-aligned bounding box of the line.

func (Line) End added in v0.9.1

func (l Line) End() Point

End returns the ending point of the line.

func (Line) Eval added in v0.9.1

func (l Line) Eval(t float64) Point

Eval evaluates the line at parameter t (0 to 1). t=0 returns P0, t=1 returns P1.

func (Line) Length added in v0.9.1

func (l Line) Length() float64

Length returns the length of the line segment.

func (Line) Midpoint added in v0.9.1

func (l Line) Midpoint() Point

Midpoint returns the midpoint of the line segment.

func (Line) Reversed added in v0.9.1

func (l Line) Reversed() Line

Reversed returns a copy of the line with endpoints swapped.

func (Line) Start added in v0.9.1

func (l Line) Start() Point

Start returns the starting point of the line.

func (Line) Subdivide added in v0.9.1

func (l Line) Subdivide() (Line, Line)

Subdivide splits the line at t=0.5 into two halves.

func (Line) Subsegment added in v0.9.1

func (l Line) Subsegment(t0, t1 float64) Line

Subsegment returns the portion of the line from t0 to t1.

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 LinearGradientBrush added in v0.12.0

type LinearGradientBrush struct {
	Start  Point       // Start point of the gradient
	End    Point       // End point of the gradient
	Stops  []ColorStop // Color stops defining the gradient
	Extend ExtendMode  // How gradient extends beyond bounds
}

LinearGradientBrush represents a linear color transition between two points. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.

LinearGradientBrush follows the vello/peniko gradient model, providing professional-quality gradients for 2D graphics.

Example:

gradient := gg.NewLinearGradientBrush(0, 0, 100, 0).
    AddColorStop(0, gg.Red).
    AddColorStop(0.5, gg.Yellow).
    AddColorStop(1, gg.Blue)
ctx.SetFillBrush(gradient)

func NewLinearGradientBrush added in v0.12.0

func NewLinearGradientBrush(x0, y0, x1, y1 float64) *LinearGradientBrush

NewLinearGradientBrush creates a new linear gradient from (x0, y0) to (x1, y1).

func (*LinearGradientBrush) AddColorStop added in v0.12.0

func (g *LinearGradientBrush) AddColorStop(offset float64, c RGBA) *LinearGradientBrush

AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.

func (*LinearGradientBrush) ColorAt added in v0.12.0

func (g *LinearGradientBrush) ColorAt(x, y float64) RGBA

ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.

func (*LinearGradientBrush) SetExtend added in v0.12.0

SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.

type Mask added in v0.14.0

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

Mask represents an alpha mask for compositing operations. Values range from 0 (fully transparent) to 255 (fully opaque).

func NewMask added in v0.14.0

func NewMask(width, height int) *Mask

NewMask creates a new empty mask with the given dimensions. All values are initialized to 0 (fully transparent).

func NewMaskFromAlpha added in v0.14.0

func NewMaskFromAlpha(img image.Image) *Mask

NewMaskFromAlpha creates a mask from an image's alpha channel.

func (*Mask) At added in v0.14.0

func (m *Mask) At(x, y int) uint8

At returns the mask value at (x, y). Returns 0 for coordinates outside the mask bounds.

func (*Mask) Bounds added in v0.14.0

func (m *Mask) Bounds() image.Rectangle

Bounds returns the mask dimensions as an image.Rectangle.

func (*Mask) Clear added in v0.14.0

func (m *Mask) Clear()

Clear clears the mask (sets all values to 0).

func (*Mask) Clone added in v0.14.0

func (m *Mask) Clone() *Mask

Clone creates a copy of the mask.

func (*Mask) Data added in v0.14.0

func (m *Mask) Data() []uint8

Data returns the underlying mask data slice. This is useful for advanced operations.

func (*Mask) Fill added in v0.14.0

func (m *Mask) Fill(value uint8)

Fill fills the entire mask with a value.

func (*Mask) Height added in v0.14.0

func (m *Mask) Height() int

Height returns the mask height.

func (*Mask) Invert added in v0.14.0

func (m *Mask) Invert()

Invert inverts all mask values (255 - value).

func (*Mask) Set added in v0.14.0

func (m *Mask) Set(x, y int, value uint8)

Set sets the mask value at (x, y). Coordinates outside the mask bounds are ignored.

func (*Mask) Width added in v0.14.0

func (m *Mask) Width() int

Width returns the mask width.

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.
	//
	// Deprecated: Use Brush instead. Pattern is maintained for backward compatibility.
	Pattern Pattern

	// Brush is the fill or stroke brush (vello/peniko pattern).
	// When both Brush and Pattern are set, Brush takes precedence.
	// Use SetBrush() to set the brush, which also updates Pattern for compatibility.
	Brush Brush

	// LineWidth is the width of strokes.
	//
	// Deprecated: Use Stroke.Width instead. Maintained for backward compatibility.
	LineWidth float64

	// LineCap is the shape of line endpoints.
	//
	// Deprecated: Use Stroke.Cap instead. Maintained for backward compatibility.
	LineCap LineCap

	// LineJoin is the shape of line joins.
	//
	// Deprecated: Use Stroke.Join instead. Maintained for backward compatibility.
	LineJoin LineJoin

	// MiterLimit is the miter limit for sharp joins.
	//
	// Deprecated: Use Stroke.MiterLimit instead. Maintained for backward compatibility.
	MiterLimit float64

	// FillRule is the fill rule for paths
	FillRule FillRule

	// Antialias enables anti-aliasing
	Antialias bool

	// Stroke is the unified stroke style configuration.
	// This is the preferred way to configure stroke properties.
	// When Stroke is set, it takes precedence over the individual
	// LineWidth, LineCap, LineJoin, and MiterLimit fields.
	Stroke *Stroke
}

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.

func (*Paint) ColorAt added in v0.12.0

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

ColorAt returns the color at the given position. It uses Brush if set, otherwise falls back to Pattern.

func (*Paint) EffectiveDash added in v0.12.0

func (p *Paint) EffectiveDash() *Dash

EffectiveDash returns the effective dash pattern. Returns nil if no dash is set (solid line).

func (*Paint) EffectiveLineCap added in v0.12.0

func (p *Paint) EffectiveLineCap() LineCap

EffectiveLineCap returns the effective line cap. If Stroke is set, uses Stroke.Cap; otherwise uses LineCap.

func (*Paint) EffectiveLineJoin added in v0.12.0

func (p *Paint) EffectiveLineJoin() LineJoin

EffectiveLineJoin returns the effective line join. If Stroke is set, uses Stroke.Join; otherwise uses LineJoin.

func (*Paint) EffectiveLineWidth added in v0.12.0

func (p *Paint) EffectiveLineWidth() float64

EffectiveLineWidth returns the effective line width. If Stroke is set, uses Stroke.Width; otherwise uses LineWidth.

func (*Paint) EffectiveMiterLimit added in v0.12.0

func (p *Paint) EffectiveMiterLimit() float64

EffectiveMiterLimit returns the effective miter limit. If Stroke is set, uses Stroke.MiterLimit; otherwise uses MiterLimit.

func (*Paint) GetBrush added in v0.12.0

func (p *Paint) GetBrush() Brush

GetBrush returns the current brush. If Brush is nil, it returns a brush converted from Pattern.

func (*Paint) GetStroke added in v0.12.0

func (p *Paint) GetStroke() Stroke

GetStroke returns the effective stroke style. If Stroke is set, returns a copy of it. Otherwise, constructs a Stroke from the legacy fields.

func (*Paint) IsDashed added in v0.12.0

func (p *Paint) IsDashed() bool

IsDashed returns true if the current stroke uses a dash pattern.

func (*Paint) SetBrush added in v0.12.0

func (p *Paint) SetBrush(b Brush)

SetBrush sets the brush for this Paint. It also updates the Pattern field for backward compatibility.

func (*Paint) SetStroke added in v0.12.0

func (p *Paint) SetStroke(s Stroke)

SetStroke sets the stroke style. This also updates the legacy fields for backward compatibility.

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) Area added in v0.9.1

func (p *Path) Area() float64

Area returns the signed area enclosed by the path. Positive for clockwise paths, negative for counter-clockwise. Uses the shoelace formula extended for curves (Green's theorem). Only closed subpaths contribute to the area.

func (*Path) BoundingBox added in v0.9.1

func (p *Path) BoundingBox() Rect

BoundingBox returns the tight axis-aligned bounding box of the path. Uses curve extrema for accuracy.

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) Clone added in v0.14.0

func (p *Path) Clone() *Path

Clone creates a deep copy of the path.

func (*Path) Close

func (p *Path) Close()

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

func (*Path) Contains added in v0.9.1

func (p *Path) Contains(pt Point) bool

Contains tests if a point is inside the path using the non-zero fill rule.

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) Flatten added in v0.9.1

func (p *Path) Flatten(tolerance float64) []Point

Flatten converts all curves to line segments with given tolerance. tolerance is the maximum distance from the curve.

func (*Path) FlattenCallback added in v0.9.1

func (p *Path) FlattenCallback(tolerance float64, fn func(pt Point))

FlattenCallback calls fn for each point in the flattened path. More efficient than Flatten() as it avoids allocation.

func (*Path) HasCurrentPoint added in v0.14.0

func (p *Path) HasCurrentPoint() bool

HasCurrentPoint returns true if the path has a current point. A path has a current point after MoveTo, LineTo, or any curve operation.

func (*Path) Length added in v0.9.1

func (p *Path) Length(accuracy float64) float64

Length returns the total arc length of the path. accuracy controls the precision of the approximation (smaller = more accurate).

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) Reversed added in v0.9.1

func (p *Path) Reversed() *Path

Reversed returns a new path with reversed direction. Each subpath is reversed independently.

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.

func (*Path) Winding added in v0.9.1

func (p *Path) Winding(pt Point) int

Winding returns the winding number of a point relative to the path. 0 = outside, non-zero = inside (for non-zero fill rule). Uses ray casting with a horizontal ray to the right.

type PathBuilder added in v0.14.0

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

PathBuilder provides a fluent interface for path construction. All methods return the builder for chaining.

func BuildPath added in v0.14.0

func BuildPath() *PathBuilder

BuildPath starts a new path builder.

func (*PathBuilder) Build added in v0.14.0

func (b *PathBuilder) Build() *Path

Build returns the constructed path.

func (*PathBuilder) Circle added in v0.14.0

func (b *PathBuilder) Circle(cx, cy, r float64) *PathBuilder

Circle adds a circle to the path.

func (*PathBuilder) Close added in v0.14.0

func (b *PathBuilder) Close() *PathBuilder

Close closes the current subpath.

func (*PathBuilder) CubicTo added in v0.14.0

func (b *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *PathBuilder

CubicTo draws a cubic Bezier curve.

func (*PathBuilder) Ellipse added in v0.14.0

func (b *PathBuilder) Ellipse(cx, cy, rx, ry float64) *PathBuilder

Ellipse adds an ellipse to the path.

func (*PathBuilder) LineTo added in v0.14.0

func (b *PathBuilder) LineTo(x, y float64) *PathBuilder

LineTo draws a line to a position.

func (*PathBuilder) MoveTo added in v0.14.0

func (b *PathBuilder) MoveTo(x, y float64) *PathBuilder

MoveTo moves to a new position.

func (*PathBuilder) Path added in v0.14.0

func (b *PathBuilder) Path() *Path

Path returns the constructed path (alias for Build).

func (*PathBuilder) Polygon added in v0.14.0

func (b *PathBuilder) Polygon(cx, cy, radius float64, sides int) *PathBuilder

Polygon adds a regular polygon to the path.

func (*PathBuilder) QuadTo added in v0.14.0

func (b *PathBuilder) QuadTo(cx, cy, x, y float64) *PathBuilder

QuadTo draws a quadratic Bezier curve.

func (*PathBuilder) Rect added in v0.14.0

func (b *PathBuilder) Rect(x, y, w, h float64) *PathBuilder

Rect adds a rectangle to the path.

func (*PathBuilder) RoundRect added in v0.14.0

func (b *PathBuilder) RoundRect(x, y, w, h, r float64) *PathBuilder

RoundRect adds a rounded rectangle to the path.

func (*PathBuilder) Star added in v0.14.0

func (b *PathBuilder) Star(cx, cy, outerRadius, innerRadius float64, points int) *PathBuilder

Star adds a star shape to 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.

func PatternFromBrush deprecated added in v0.12.0

func PatternFromBrush(b Brush) Pattern

PatternFromBrush converts a Brush to a legacy Pattern. This is a compatibility helper for code that still uses Pattern.

Deprecated: Use Brush types directly instead of Pattern.

type Pixmap

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

Pixmap represents a rectangular pixel buffer. It implements both image.Image (read-only) and draw.Image (read-write) interfaces, making it compatible with Go's standard image ecosystem including text rendering via golang.org/x/image/font.

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) EncodeJPEG added in v0.14.0

func (p *Pixmap) EncodeJPEG(w io.Writer, quality int) error

EncodeJPEG writes the pixmap as JPEG with the given quality (1-100).

func (*Pixmap) EncodePNG added in v0.14.0

func (p *Pixmap) EncodePNG(w io.Writer) error

EncodePNG writes the pixmap as PNG to the given writer. This is useful for streaming, network output, or custom storage.

func (*Pixmap) FillSpan added in v0.5.0

func (p *Pixmap) FillSpan(x1, x2, y int, c RGBA)

FillSpan fills a horizontal span of pixels with a solid color (no blending). This is optimized for batch operations when the span is >= 16 pixels. The span is from x1 (inclusive) to x2 (exclusive) on row y.

func (*Pixmap) FillSpanBlend added in v0.5.0

func (p *Pixmap) FillSpanBlend(x1, x2, y int, c RGBA)

FillSpanBlend fills a horizontal span with blending. This uses batch blending operations for spans >= 16 pixels.

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) Set added in v0.9.1

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

Set implements the draw.Image interface. This allows Pixmap to be used as a destination for image drawing operations, including text rendering via golang.org/x/image/font.

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 QuadBez added in v0.9.1

type QuadBez struct {
	P0, P1, P2 Point
}

QuadBez represents a quadratic Bezier curve with control points P0, P1, P2. P0 is the start point, P1 is the control point, P2 is the end point.

func NewQuadBez added in v0.9.1

func NewQuadBez(p0, p1, p2 Point) QuadBez

NewQuadBez creates a new quadratic Bezier curve.

func (QuadBez) BoundingBox added in v0.9.1

func (q QuadBez) BoundingBox() Rect

BoundingBox returns the tight axis-aligned bounding box of the curve.

func (QuadBez) End added in v0.9.1

func (q QuadBez) End() Point

End returns the ending point of the curve.

func (QuadBez) Eval added in v0.9.1

func (q QuadBez) Eval(t float64) Point

Eval evaluates the curve at parameter t (0 to 1) using de Casteljau's algorithm.

func (QuadBez) Extrema added in v0.9.1

func (q QuadBez) Extrema() []float64

Extrema returns parameter values where the derivative is zero (extrema points). Used for computing tight bounding boxes.

func (QuadBez) Raise added in v0.9.1

func (q QuadBez) Raise() CubicBez

Raise elevates the quadratic to a cubic Bezier curve. Returns an exact cubic representation of this quadratic.

func (QuadBez) Start added in v0.9.1

func (q QuadBez) Start() Point

Start returns the starting point of the curve.

func (QuadBez) Subdivide added in v0.9.1

func (q QuadBez) Subdivide() (QuadBez, QuadBez)

Subdivide splits the curve at t=0.5 into two halves using de Casteljau.

func (QuadBez) Subsegment added in v0.9.1

func (q QuadBez) Subsegment(t0, t1 float64) QuadBez

Subsegment returns the portion of the curve from t0 to t1.

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 RadialGradientBrush added in v0.12.0

type RadialGradientBrush struct {
	Center      Point       // Center of the gradient circle
	Focus       Point       // Focal point (can differ from center)
	StartRadius float64     // Inner radius where gradient begins (t=0)
	EndRadius   float64     // Outer radius where gradient ends (t=1)
	Stops       []ColorStop // Color stops defining the gradient
	Extend      ExtendMode  // How gradient extends beyond bounds
}

RadialGradientBrush represents a radial color transition. Colors radiate from a focal point within a circle defined by center and end radius. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.

RadialGradientBrush follows the vello/peniko gradient model, supporting both simple radial gradients (focus at center) and focal gradients (focus offset from center for spotlight effects).

Example:

// Simple radial gradient
gradient := gg.NewRadialGradientBrush(50, 50, 0, 50).
    AddColorStop(0, gg.White).
    AddColorStop(1, gg.Black)

// Focal gradient (spotlight effect)
spotlight := gg.NewRadialGradientBrush(50, 50, 0, 50).
    SetFocus(30, 30).
    AddColorStop(0, gg.White).
    AddColorStop(1, gg.Black)

func NewRadialGradientBrush added in v0.12.0

func NewRadialGradientBrush(cx, cy, startRadius, endRadius float64) *RadialGradientBrush

NewRadialGradientBrush creates a new radial gradient. The gradient transitions from startRadius to endRadius around (cx, cy). Focus defaults to center.

func (*RadialGradientBrush) AddColorStop added in v0.12.0

func (g *RadialGradientBrush) AddColorStop(offset float64, c RGBA) *RadialGradientBrush

AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.

func (*RadialGradientBrush) ColorAt added in v0.12.0

func (g *RadialGradientBrush) ColorAt(x, y float64) RGBA

ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.

func (*RadialGradientBrush) SetExtend added in v0.12.0

SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.

func (*RadialGradientBrush) SetFocus added in v0.12.0

func (g *RadialGradientBrush) SetFocus(fx, fy float64) *RadialGradientBrush

SetFocus sets the focal point of the gradient. A focal point different from center creates an asymmetric gradient. Returns the gradient for method chaining.

type Rect added in v0.9.1

type Rect struct {
	Min, Max Point
}

Rect represents an axis-aligned rectangle. Min is the top-left corner (minimum coordinates). Max is the bottom-right corner (maximum coordinates).

func NewRect added in v0.9.1

func NewRect(p1, p2 Point) Rect

NewRect creates a rectangle from two points. The points are normalized so Min <= Max.

func (Rect) Contains added in v0.9.1

func (r Rect) Contains(p Point) bool

Contains returns true if the point is inside the rectangle.

func (Rect) Height added in v0.9.1

func (r Rect) Height() float64

Height returns the height of the rectangle.

func (Rect) Union added in v0.9.1

func (r Rect) Union(other Rect) Rect

Union returns the smallest rectangle containing both r and other.

func (Rect) Width added in v0.9.1

func (r Rect) Width() float64

Width returns the width of the rectangle.

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 SolidBrush added in v0.12.0

type SolidBrush struct {
	// Color is the solid color of this brush.
	Color RGBA
}

SolidBrush is a single-color brush. It implements the Brush interface and always returns the same color.

func Solid added in v0.12.0

func Solid(c RGBA) SolidBrush

Solid creates a SolidBrush from an RGBA color.

Example:

brush := gg.Solid(gg.Red)
brush := gg.Solid(gg.RGBA{R: 1, G: 0, B: 0, A: 1})

func SolidHex added in v0.12.0

func SolidHex(hex string) SolidBrush

SolidHex creates a SolidBrush from a hex color string. Supports formats: "RGB", "RGBA", "RRGGBB", "RRGGBBAA", with optional '#' prefix.

Example:

brush := gg.SolidHex("#FF5733")
brush := gg.SolidHex("FF5733")
brush := gg.SolidHex("#F53")

func SolidRGB added in v0.12.0

func SolidRGB(r, g, b float64) SolidBrush

SolidRGB creates a SolidBrush from RGB components (0-1 range). Alpha is set to 1.0 (fully opaque).

Example:

brush := gg.SolidRGB(1, 0, 0) // Red
brush := gg.SolidRGB(0.5, 0.5, 0.5) // Gray

func SolidRGBA added in v0.12.0

func SolidRGBA(r, g, b, a float64) SolidBrush

SolidRGBA creates a SolidBrush from RGBA components (0-1 range).

Example:

brush := gg.SolidRGBA(1, 0, 0, 0.5) // Semi-transparent red

func (SolidBrush) ColorAt added in v0.12.0

func (b SolidBrush) ColorAt(_, _ float64) RGBA

ColorAt implements Brush. Returns the solid color regardless of position.

func (SolidBrush) Lerp added in v0.12.0

func (b SolidBrush) Lerp(other SolidBrush, t float64) SolidBrush

Lerp performs linear interpolation between two solid brushes. Returns a new SolidBrush with the interpolated color.

Example:

red := gg.Solid(gg.Red)
blue := gg.Solid(gg.Blue)
purple := red.Lerp(blue, 0.5)

func (SolidBrush) Opaque added in v0.12.0

func (b SolidBrush) Opaque() SolidBrush

Opaque returns a new SolidBrush with alpha set to 1.0.

func (SolidBrush) Transparent added in v0.12.0

func (b SolidBrush) Transparent() SolidBrush

Transparent returns a new SolidBrush with alpha set to 0.0.

func (SolidBrush) WithAlpha added in v0.12.0

func (b SolidBrush) WithAlpha(alpha float64) SolidBrush

WithAlpha returns a new SolidBrush with the specified alpha value. The RGB components are preserved.

Example:

opaqueBrush := gg.Solid(gg.Red)
semiBrush := opaqueBrush.WithAlpha(0.5)

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.

type Stroke added in v0.12.0

type Stroke struct {
	// Width is the line width in pixels. Default: 1.0
	Width float64

	// Cap is the shape of line endpoints. Default: LineCapButt
	Cap LineCap

	// Join is the shape of line joins. Default: LineJoinMiter
	Join LineJoin

	// MiterLimit is the limit for miter joins before they become bevels.
	// Default: 4.0 (common default, matches SVG)
	MiterLimit float64

	// Dash is the dash pattern for the stroke.
	// nil means a solid line (no dashing).
	Dash *Dash
}

Stroke defines the style for stroking paths. It encapsulates all stroke-related properties in a single struct, following the tiny-skia/kurbo pattern for unified stroke configuration.

func Bold added in v0.12.0

func Bold() Stroke

Bold returns a bold stroke (5 pixels).

func DashedStroke added in v0.12.0

func DashedStroke(lengths ...float64) Stroke

DashedStroke returns a dashed stroke with the given pattern.

func DefaultStroke added in v0.12.0

func DefaultStroke() Stroke

DefaultStroke returns a Stroke with default settings. This creates a solid 1-pixel line with butt caps and miter joins.

func DottedStroke added in v0.12.0

func DottedStroke() Stroke

DottedStroke returns a dotted stroke. Uses round caps with equal dash and gap (1, 2 pattern with 2px width).

func RoundStroke added in v0.12.0

func RoundStroke() Stroke

RoundStroke returns a stroke with round caps and joins.

func SquareStroke added in v0.12.0

func SquareStroke() Stroke

SquareStroke returns a stroke with square caps.

func Thick added in v0.12.0

func Thick() Stroke

Thick returns a thick stroke (3 pixels).

func Thin added in v0.12.0

func Thin() Stroke

Thin returns a thin stroke (0.5 pixels).

func (Stroke) Clone added in v0.12.0

func (s Stroke) Clone() Stroke

Clone creates a deep copy of the Stroke.

func (Stroke) IsDashed added in v0.12.0

func (s Stroke) IsDashed() bool

IsDashed returns true if this stroke has a dash pattern.

func (Stroke) WithCap added in v0.12.0

func (s Stroke) WithCap(lineCap LineCap) Stroke

WithCap returns a copy of the Stroke with the given line cap style.

func (Stroke) WithDash added in v0.12.0

func (s Stroke) WithDash(dash *Dash) Stroke

WithDash returns a copy of the Stroke with the given dash pattern. Pass nil to remove dashing and return to solid lines.

func (Stroke) WithDashOffset added in v0.12.0

func (s Stroke) WithDashOffset(offset float64) Stroke

WithDashOffset returns a copy of the Stroke with the dash offset set. If there is no dash pattern, this has no effect.

func (Stroke) WithDashPattern added in v0.12.0

func (s Stroke) WithDashPattern(lengths ...float64) Stroke

WithDashPattern returns a copy of the Stroke with a dash pattern created from the given lengths.

Example:

stroke.WithDashPattern(5, 3) // 5 units dash, 3 units gap

func (Stroke) WithJoin added in v0.12.0

func (s Stroke) WithJoin(join LineJoin) Stroke

WithJoin returns a copy of the Stroke with the given line join style.

func (Stroke) WithMiterLimit added in v0.12.0

func (s Stroke) WithMiterLimit(limit float64) Stroke

WithMiterLimit returns a copy of the Stroke with the given miter limit. The miter limit controls when miter joins are converted to bevel joins. A value of 1.0 effectively disables miter joins.

func (Stroke) WithWidth added in v0.12.0

func (s Stroke) WithWidth(w float64) Stroke

WithWidth returns a copy of the Stroke with the given width.

type SweepGradientBrush added in v0.12.0

type SweepGradientBrush struct {
	Center     Point       // Center of the sweep
	StartAngle float64     // Start angle in radians
	EndAngle   float64     // End angle in radians (if 0, defaults to StartAngle + 2*Pi)
	Stops      []ColorStop // Color stops defining the gradient
	Extend     ExtendMode  // How gradient extends beyond bounds
}

SweepGradientBrush represents an angular (conic) color transition around a center point. Colors sweep from StartAngle to EndAngle. Also known as a conic gradient. It implements the Brush interface and supports multiple color stops, proper sRGB color interpolation, and configurable extend modes.

SweepGradientBrush follows the vello/peniko gradient model, providing professional-quality angular gradients for effects like color wheels, pie charts, and radar displays.

Example:

// Color wheel
wheel := gg.NewSweepGradientBrush(50, 50, 0).
    AddColorStop(0, gg.Red).
    AddColorStop(0.166, gg.Yellow).
    AddColorStop(0.333, gg.Green).
    AddColorStop(0.5, gg.Cyan).
    AddColorStop(0.666, gg.Blue).
    AddColorStop(0.833, gg.Magenta).
    AddColorStop(1, gg.Red)

func NewSweepGradientBrush added in v0.12.0

func NewSweepGradientBrush(cx, cy, startAngle float64) *SweepGradientBrush

NewSweepGradientBrush creates a new sweep (conic) gradient centered at (cx, cy). startAngle is the angle where the gradient begins (in radians). The gradient sweeps a full 360 degrees by default.

func (*SweepGradientBrush) AddColorStop added in v0.12.0

func (g *SweepGradientBrush) AddColorStop(offset float64, c RGBA) *SweepGradientBrush

AddColorStop adds a color stop at the specified offset. Offset should be in the range [0, 1]. Returns the gradient for method chaining.

func (*SweepGradientBrush) ColorAt added in v0.12.0

func (g *SweepGradientBrush) ColorAt(x, y float64) RGBA

ColorAt returns the color at the given point. Implements the Pattern and Brush interfaces.

func (*SweepGradientBrush) SetEndAngle added in v0.12.0

func (g *SweepGradientBrush) SetEndAngle(endAngle float64) *SweepGradientBrush

SetEndAngle sets the end angle of the sweep. Returns the gradient for method chaining.

func (*SweepGradientBrush) SetExtend added in v0.12.0

func (g *SweepGradientBrush) SetExtend(mode ExtendMode) *SweepGradientBrush

SetExtend sets the extend mode for the gradient. Returns the gradient for method chaining.

type Vec2 added in v0.9.1

type Vec2 struct {
	X, Y float64
}

Vec2 represents a 2D displacement vector. Unlike Point which represents a position, Vec2 represents a direction and magnitude. This semantic distinction helps make code clearer when working with curve geometry.

func PointToVec2 added in v0.9.1

func PointToVec2(p Point) Vec2

PointToVec2 converts Point to Vec2. Useful when you need to treat a position as a displacement.

func V2 added in v0.9.1

func V2(x, y float64) Vec2

V2 is a convenience function to create a Vec2.

func (Vec2) Add added in v0.9.1

func (v Vec2) Add(w Vec2) Vec2

Add returns the sum of two vectors.

func (Vec2) Angle added in v0.9.1

func (v Vec2) Angle(w Vec2) float64

Angle returns the angle between two vectors in radians.

func (Vec2) Approx added in v0.9.1

func (v Vec2) Approx(w Vec2, epsilon float64) bool

Approx returns true if two vectors are approximately equal within epsilon.

func (Vec2) Atan2 added in v0.9.1

func (v Vec2) Atan2() float64

Atan2 returns the angle of the vector in radians.

func (Vec2) Cross added in v0.9.1

func (v Vec2) Cross(w Vec2) float64

Cross returns the 2D cross product (scalar). This is the z-component of the 3D cross product with z=0. Useful for determining the sign of the angle between vectors.

func (Vec2) Div added in v0.9.1

func (v Vec2) Div(s float64) Vec2

Div returns the vector divided by a scalar.

func (Vec2) Dot added in v0.9.1

func (v Vec2) Dot(w Vec2) float64

Dot returns the dot product of two vectors.

func (Vec2) IsZero added in v0.9.1

func (v Vec2) IsZero() bool

IsZero returns true if the vector is the zero vector.

func (Vec2) Length added in v0.9.1

func (v Vec2) Length() float64

Length returns the length (magnitude) of the vector.

func (Vec2) LengthSq added in v0.9.1

func (v Vec2) LengthSq() float64

LengthSq returns the squared length of the vector. This is faster than Length() when you only need to compare magnitudes.

func (Vec2) Lerp added in v0.9.1

func (v Vec2) Lerp(w Vec2, t float64) Vec2

Lerp performs linear interpolation between two vectors. t=0 returns v, t=1 returns w, intermediate values interpolate.

func (Vec2) Mul added in v0.9.1

func (v Vec2) Mul(s float64) Vec2

Mul returns the vector scaled by a scalar.

func (Vec2) Neg added in v0.9.1

func (v Vec2) Neg() Vec2

Neg returns the negation of the vector.

func (Vec2) Normalize added in v0.9.1

func (v Vec2) Normalize() Vec2

Normalize returns a unit vector in the same direction. Returns zero vector if the original vector has zero length.

func (Vec2) Perp added in v0.9.1

func (v Vec2) Perp() Vec2

Perp returns the perpendicular vector (rotated 90 degrees counter-clockwise).

func (Vec2) Rotate added in v0.9.1

func (v Vec2) Rotate(angle float64) Vec2

Rotate returns the vector rotated by angle radians.

func (Vec2) Sub added in v0.9.1

func (v Vec2) Sub(w Vec2) Vec2

Sub returns the difference of two vectors.

func (Vec2) ToPoint added in v0.9.1

func (v Vec2) ToPoint() Point

ToPoint converts Vec2 to Point. Useful when you need to treat a displacement as a position.

Directories

Path Synopsis
Package backend provides a pluggable rendering backend abstraction.
Package backend provides a pluggable rendering backend abstraction.
wgpu
Package wgpu provides a GPU-accelerated rendering backend using gogpu/wgpu.
Package wgpu provides a GPU-accelerated rendering backend using gogpu/wgpu.
Package cache provides generic, high-performance caching primitives.
Package cache provides generic, high-performance caching primitives.
cmd
ggdemo command
Command ggdemo demonstrates the gg 2D graphics library.
Command ggdemo demonstrates the gg 2D graphics library.
examples
basic command
clipping command
Package main demonstrates the clipping API in gogpu/gg.
Package main demonstrates the clipping API in gogpu/gg.
gpu command
Package main demonstrates the GPU backend for gogpu/gg.
Package main demonstrates the GPU backend for gogpu/gg.
images command
Package main demonstrates image drawing capabilities in gg.
Package main demonstrates image drawing capabilities in gg.
scene command
Package main demonstrates the scene graph (retained mode) API for gogpu/gg.
Package main demonstrates the scene graph (retained mode) API for gogpu/gg.
shapes command
text command
text_fallback command
internal
blend
Package blend implements advanced separable and non-separable blend modes.
Package blend implements advanced separable and non-separable blend modes.
clip
Package clip provides geometric clipping for paths and shapes.
Package clip provides geometric clipping for paths and shapes.
color
Package color provides color space types and conversions for gg.
Package color provides color space types and conversions for gg.
filter
Package filter provides image filter implementations for the scene graph.
Package filter provides image filter implementations for the scene graph.
image
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
parallel
Package parallel provides tile-based parallel rendering infrastructure for gogpu/gg.
Package parallel provides tile-based parallel rendering infrastructure for gogpu/gg.
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.
wide
Package wide provides SIMD-friendly wide types for batch pixel processing.
Package wide provides SIMD-friendly wide types for batch pixel processing.
Package scene provides blend mode integration with internal/blend package.
Package scene provides blend mode integration with internal/blend package.
Package text provides text rendering for gg.
Package text provides text rendering for gg.
cache
Package cache provides high-performance caching for text shaping and rendering.
Package cache provides high-performance caching for text shaping and rendering.
emoji
Package emoji provides emoji and color font support for text rendering.
Package emoji provides emoji and color font support for text rendering.
msdf
Package msdf provides Multi-channel Signed Distance Field generation for high-quality, scalable text rendering on GPU.
Package msdf provides Multi-channel Signed Distance Field generation for high-quality, scalable text rendering on GPU.

Jump to

Keyboard shortcuts

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