gg

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 10 Imported by: 0

README

gg

Enterprise-Grade 2D Graphics Library for Go
Professional rendering • Pure Go • Part of GoGPU Ecosystem

CI codecov Go Reference Go Report Card License Go Version


Vision

gg is designed to become the reference 2D graphics library for the Go ecosystem — capable of powering:

  • IDEs (GoLAND, VS Code level)
  • Browsers (Chrome level)
  • Professional graphics applications

Inspired by fogleman/gg, tiny-skia, and vello.


Current: v0.8.0

Backend Abstraction — Pluggable rendering backends for CPU and GPU!

Star the repo to follow progress!


Features

Core Graphics

  • Simple API — Immediate-mode drawing API similar to HTML Canvas
  • Pure Go — No C dependencies, cross-platform
  • Rich Shapes — Rectangles, circles, ellipses, arcs, Bezier curves
  • Path Operations — MoveTo, LineTo, QuadraticTo, CubicTo
  • Transformations — Translate, rotate, scale with matrix stack
  • Colors — RGBA, hex parsing, named colors

Text Rendering (v0.2.0)

  • TrueType Fonts — Full TTF support via golang.org/x/image
  • Font Composition — MultiFace for fallback chains
  • Unicode Support — FilteredFace for emoji and special ranges
  • Zero-Allocation Iterators — Go 1.25+ iter.Seq[Glyph]

Images (v0.3.0)

  • 7 Pixel Formats — Gray8, Gray16, RGB8, RGBA8, RGBAPremul, BGRA8, BGRAPremul
  • DrawImage — Draw images with position, transforms, opacity
  • Interpolation — Nearest, Bilinear, Bicubic sampling
  • Patterns — Image patterns for fills with repeat modes
  • Mipmaps — Automatic mipmap chain generation

Clipping (v0.3.0)

  • Clip() — Clip to current path
  • ClipRect() — Fast rectangular clipping
  • ClipPreserve() — Clip keeping path for stroke
  • Hierarchical — Push/Pop state preserves clip regions

Compositing (v0.3.0)

  • Porter-Duff — 14 blend modes (SrcOver, DstIn, Xor, etc.)
  • Advanced Blends — Screen, Overlay, Darken, Lighten, ColorDodge, etc.

Color Pipeline & Layers (v0.4.0)

  • Layer API — PushLayer/PopLayer for isolated drawing with blend modes
  • HSL Blend Modes — Hue, Saturation, Color, Luminosity (W3C spec)
  • Linear Blending — Correct sRGB ↔ Linear color space pipeline
  • ColorSpace Package — ColorF32/ColorU8 types with conversions

SIMD Optimization (v0.5.0)

  • Fast div255 — Shift approximation, no division (2.4x faster)
  • sRGB LUTs — Pre-computed lookup tables (260x faster than math.Pow)
  • Wide Types — U16x16/F32x8 for batch processing (16 pixels at once)
  • Batch Blending — All 14 Porter-Duff modes + 7 advanced modes
  • Auto-vectorization — Fixed-size arrays trigger Go compiler SIMD
  • FillSpan — Optimized span filling for rasterizer integration

Parallel Rendering (v0.6.0)

  • TileGrid — Canvas divided into 64x64 pixel tiles for independent rendering
  • WorkerPool — Goroutine pool with work stealing for load balancing
  • ParallelRasterizer — Clear, FillRect, Composite operations across tiles
  • Lock-Free DirtyRegion — Atomic bitmap tracking for changed tiles (10.9ns/mark)
  • Visual Regression Tests — Pixel-perfect comparison of parallel vs serial
  • Scaling Benchmarks — Linear scaling with 1, 2, 4, 8+ cores

Scene Graph (v0.7.0)

  • Dual-Stream Encoding — GPU-ready command buffer (vello pattern)
  • Scene API — Fill, Stroke, PushLayer, PopLayer, PushClip, transforms
  • 13 Shape Types — Rect, Circle, Ellipse, Line, Polygon, RoundedRect...
  • 29 Blend Modes — 14 Porter-Duff + 11 Advanced + 4 HSL
  • Filter Effects — Gaussian blur, drop shadow, color matrix (10 presets)
  • LRU Layer Cache — 64MB default, configurable, 90ns Get / 393ns Put
  • SceneBuilder — Fluent API for ergonomic scene construction
  • Parallel Renderer — TileGrid + WorkerPool integration

Backend Abstraction (v0.8.0)

  • RenderBackend Interface — Pluggable rendering backends
  • SoftwareBackend — CPU-based rendering (default)
  • Backend Registry — Auto-selection with priority (wgpu > software)
  • Fallback Mechanism — Graceful degradation when GPU unavailable

Coming Soon (v0.9.0+)

  • GPU Backend — Hardware acceleration via gogpu/wgpu

Installation

go get github.com/gogpu/gg

Requirements: Go 1.25+


Quick Start

package main

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

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

    // Draw shapes
    ctx.SetColor(gg.Hex("#3498db"))
    ctx.DrawCircle(256, 256, 100)
    ctx.Fill()

    // Load font and draw text
    source, _ := text.NewFontSourceFromFile("arial.ttf")
    defer source.Close()

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

    ctx.SavePNG("output.png")
}

Image Drawing

// Load image
img, _ := gg.LoadImage("photo.png")

// Draw at position
ctx.DrawImage(img, 100, 100)

// Draw with options
ctx.DrawImageEx(img, gg.DrawImageOptions{
    X:       200,
    Y:       200,
    ScaleX:  0.5,
    ScaleY:  0.5,
    Opacity: 0.8,
})

Clipping

// Clip to circle
ctx.DrawCircle(256, 256, 100)
ctx.Clip()

// Everything drawn now is clipped
ctx.SetColor(gg.Red)
ctx.DrawRectangle(0, 0, 512, 512)
ctx.Fill()

// Reset clip
ctx.ResetClip()

// Or use Push/Pop for scoped clipping
ctx.Push()
ctx.ClipRect(100, 100, 200, 200)
// ... draw clipped content ...
ctx.Pop()

Text Rendering

// Load font (heavyweight, share across app)
source, err := text.NewFontSourceFromFile("Roboto.ttf")
defer source.Close()

// Create face (lightweight, per size)
face := source.Face(24)

// Draw text
ctx.SetFont(face)
ctx.DrawString("Hello World!", 50, 100)
ctx.DrawStringAnchored("Centered", 256, 256, 0.5, 0.5)

// Measure text
w, h := ctx.MeasureString("Hello")

// Font fallback for emoji
emoji, _ := text.NewFontSourceFromFile("NotoEmoji.ttf")
multiFace, _ := text.NewMultiFace(
    source.Face(24),
    text.NewFilteredFace(emoji.Face(24), text.RangeEmoji),
)
ctx.SetFont(multiFace)
ctx.DrawString("Hello! :)", 50, 150)

Roadmap to v1.0.0

Version Focus Status
v0.1.0 Core shapes, software renderer Released
v0.2.0 Text rendering Released
v0.3.0 Images, clipping, compositing Released
v0.4.0 Color pipeline, layer API Released
v0.5.0 SIMD optimization Released
v0.6.0 Parallel rendering Released
v0.7.0 Scene graph (retained mode) Released
v0.8.0 Backend abstraction In Progress
v0.9.0 GPU acceleration Planned
v1.0.0 Production release Target

Architecture (v1.0.0 Target)

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

Part of GoGPU Ecosystem

gogpu is a Pure Go GPU Computing Ecosystem — professional graphics libraries for Go.

Component Description Version
gogpu/gogpu GPU framework v0.3.0
gogpu/wgpu Pure Go WebGPU v0.4.0
gogpu/naga Shader compiler v0.4.0
gogpu/gg 2D graphics v0.7.0

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 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 (
	// 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.

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

type BlendMode = intImage.BlendMode

BlendMode defines how source pixels are blended with destination pixels.

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) 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) 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) 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) 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) 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 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, and clip).

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) 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) 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) 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) 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 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 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 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) 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) 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
Package backend provides a pluggable rendering backend abstraction.
Package backend provides a pluggable rendering backend abstraction.
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.
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.

Jump to

Keyboard shortcuts

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