gctx2d

package module
v0.0.0-...-ee34b8e Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0

README

gctx2d

Canvas-style bindings for https://github.com/gogpu/gogpu wgpu pipeline

canvas, err := gctx2d.NewOffscreenCanvas(device, 512, 512)
if err != nil {
	return err
}

defer canvas.Release()

ctx, err := canvas.GetContext()
if err != nil {
	return err
}

ctx.SetFillStyle(gctx2d.ColorWhite)
ctx.Rect(0, 0, 512, 512)
ctx.Fill()

ctx.SetShadowColor(gctx2d.Color{A: 0.35})
ctx.SetShadowBlur(12)
ctx.SetGlobalAlpha(0.9)
ctx.SetFillStyle(gctx2d.ColorBlack)
ctx.Circle(256, 256, 64)
ctx.Fill()

if err := canvas.Flush(nil); err != nil {
	return err
}

img := canvas.Image("hud-layer")
ctx2, err := anotherCanvas.GetContext()
if err != nil {
	return err
}

ctx2.DrawImageBounds(img, 32, 32, 256, 256)

Documentation

Index

Constants

Variables

View Source
var (
	ColorTransparent = RGBA(0, 0, 0, 0)
	ColorWhite       = RGBA(1, 1, 1, 1)
	ColorBlack       = RGBA(0, 0, 0, 1)
	ColorRed         = RGBA(1, 0, 0, 1)
	ColorGreen       = RGBA(0, 1, 0, 1)
	ColorBlue        = RGBA(0, 0, 1, 1)
	ColorYellow      = RGBA(1, 1, 0, 1)
	ColorCyan        = RGBA(0, 1, 1, 1)
	ColorMagenta     = RGBA(1, 0, 1, 1)
	ColorOrange      = RGBA(1, 0.5, 0, 1)
	ColorPurple      = RGBA(0.5, 0, 0.5, 1)
	ColorPink        = RGBA(1, 0.75, 0.8, 1)
	ColorGray        = RGBA(0.5, 0.5, 0.5, 1)
)

Functions

func DefaultFontName

func DefaultFontName() (name string)

Types

type Color

type Color struct {
	R float32
	G float32
	B float32
	A float32
}

func RGBA

func RGBA(r, g, b, a float32) Color

Color represents a color in RGBA format, where each component is a float32 in the range [0, 1].

type Context

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

func NewContext

func NewContext(device *wgpu.Device, targetFormat gputypes.TextureFormat) (renderer *Context, err error)

NewContext creates a new UI renderer with the specified default font. The fontPath should point to a .ttf/.otf file on the user's system, and fontSize is the default pixel size for rendering text. If fontPath is empty, it will attempt to find a common system font automatically.

func (*Context) Arc

func (r *Context) Arc(cx, cy, radius, startAngle, endAngle float32, counterClockwise bool)

Arc appends a circular arc to the current canvas-style path. Angles are in radians.

func (*Context) Begin

func (r *Context) Begin(width, height int)

Begin starts a new UI frame with the specified dimensions. It must be called before issuing any draw calls.

func (*Context) BeginPath

func (r *Context) BeginPath()

BeginPath clears the current canvas-style path.

func (*Context) BezierCurveTo

func (r *Context) BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32)

BezierCurveTo appends a cubic Bezier curve to the current canvas-style path.

func (*Context) Circle

func (r *Context) Circle(cx, cy, radius float32)

Circle appends a closed circular subpath. Call Fill or Stroke to draw it.

func (*Context) ClosePath

func (r *Context) ClosePath()

ClosePath closes the current canvas-style subpath.

func (*Context) CubicCurveTo

func (r *Context) CubicCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32)

CubicCurveTo is a compatibility alias for BezierCurveTo.

func (*Context) DrawImage

func (r *Context) DrawImage(img *gimage.Image, x, y float32)

DrawImage draws an image at its natural size with its top-left corner at x/y.

func (*Context) DrawImageBounds

func (r *Context) DrawImageBounds(img *gimage.Image, x, y, width, height float32)

DrawImageBounds draws an image stretched into the specified destination bounds.

func (*Context) DrawImageBoundsTransformed

func (r *Context) DrawImageBoundsTransformed(img *gimage.Image, transform Matrix, x, y, width, height float32)

DrawImageBoundsTransformed draws an image using an object-local transform that is composed with the current context transform.

func (*Context) DrawImageClipBounds

func (r *Context) DrawImageClipBounds(img *gimage.Image, x, y, width, height, x1, y1, x2, y2 float32)

DrawImageClipBounds draws a clipped source rectangle into the specified destination bounds.

func (*Context) DrawImageClipBoundsTransformed

func (r *Context) DrawImageClipBoundsTransformed(img *gimage.Image, transform Matrix, x, y, width, height, x1, y1, x2, y2 float32)

DrawImageClipBoundsTransformed draws a clipped source rectangle using an object-local transform composed with the current context transform.

func (*Context) Ellipse

func (r *Context) Ellipse(cx, cy, radiusX, radiusY, rotation, startAngle, endAngle float32, counterClockwise bool)

Ellipse appends an elliptical arc to the current canvas-style path. Angles are in radians.

func (*Context) Fill

func (r *Context) Fill()

Fill fills all current canvas-style subpaths with the current fill style. The current tessellator is a simple fan, so it is intended for convex subpaths.

func (*Context) FillText

func (r *Context) FillText(s string, x, y float32)

FillText draws an ASCII-oriented text run with the current fill style. x/y are interpreted using the current text align and baseline settings. If no font has been selected with SetFont, this is a no-op.

func (*Context) Flush

func (r *Context) Flush(target *wgpu.TextureView, clearColor *gputypes.Color) (err error)

Flush submits the accumulated draw calls to the GPU and presents them on the specified target texture view.

func (*Context) GetTransform

func (r *Context) GetTransform() Matrix

GetTransform returns the current transform matrix.

func (*Context) Line

func (r *Context) Line(x0, y0, x1, y1 float32)

Line appends an open line segment subpath. Call Stroke to draw it.

func (*Context) LineTo

func (r *Context) LineTo(x, y float32)

LineTo appends a straight line to the current canvas-style path.

func (*Context) MoveTo

func (r *Context) MoveTo(x, y float32)

MoveTo starts a new canvas-style subpath.

func (*Context) Polygon

func (r *Context) Polygon(points []Point)

Polygon appends a closed polygon subpath. Call Fill or Stroke to draw it.

func (*Context) Polyline

func (r *Context) Polyline(points []Point)

Polyline appends an open polyline subpath. Call Stroke to draw it.

func (*Context) QuadraticCurveTo

func (r *Context) QuadraticCurveTo(cpx, cpy, x, y float32)

QuadraticCurveTo appends a quadratic Bezier curve to the current canvas-style path.

func (*Context) Rect

func (r *Context) Rect(x, y, w, h float32)

Rect appends a closed rectangle subpath. Call Fill or Stroke to draw it.

func (*Context) Release

func (r *Context) Release()

Release frees all GPU resources associated with the UI renderer. It is safe to call multiple times.

func (*Context) ResetImageEffect

func (r *Context) ResetImageEffect()

ResetImageEffect restores the default built-in image effect.

func (*Context) ResetImageShader

func (r *Context) ResetImageShader()

ResetImageShader restores the default image shader for subsequent DrawImage calls.

func (*Context) ResetTransform

func (r *Context) ResetTransform()

ResetTransform restores the current canvas-style transform to the identity matrix.

func (*Context) Restore

func (r *Context) Restore()

Restore pops the most recently saved drawing state from the stack.

func (*Context) RoundedRect

func (r *Context) RoundedRect(x, y, w, h, radius float32)

RoundedRect appends a closed rounded rectangle subpath. Call Fill or Stroke to draw it.

func (*Context) Save

func (r *Context) Save()

Save pushes the current drawing state onto the stack.

func (*Context) SetEffectTime

func (r *Context) SetEffectTime(seconds float32)

SetEffectTime sets the time value used by animated image effects.

func (*Context) SetFillStyle

func (r *Context) SetFillStyle(color Color)

SetFillStyle sets the color used by Fill.

func (*Context) SetFont

func (r *Context) SetFont(size float64, handle *FontHandle, weights ...FontWeight) (err error)

SetFont selects the active font face used by FillText and StrokeText. Passing a nil handle selects the context's default font. An optional weight selects a cached synthetic weight variant. If omitted, FontWeightRegular is used.

func (*Context) SetGlobalAlpha

func (r *Context) SetGlobalAlpha(alpha float32)

SetGlobalAlpha sets the alpha multiplier applied to subsequent draw calls.

func (*Context) SetImageEffect

func (r *Context) SetImageEffect(effect ImageEffect)

SetImageEffect sets the image shader effect used by subsequent DrawImage calls.

func (*Context) SetImageShader

func (r *Context) SetImageShader(shader ImageShaderBinding)

SetImageShader sets a custom image shader used by subsequent DrawImage calls.

func (*Context) SetLineCap

func (r *Context) SetLineCap(cap LineCap)

SetLineCap sets the line cap style used by Stroke and StrokeText-like geometry.

func (*Context) SetLineJoin

func (r *Context) SetLineJoin(join LineJoin)

SetLineJoin sets the line join style used by Stroke.

func (*Context) SetLineWidth

func (r *Context) SetLineWidth(width float32)

SetLineWidth sets the stroke width used by Stroke.

func (*Context) SetMatrixTransform

func (r *Context) SetMatrixTransform(transform Matrix)

SetMatrixTransform replaces the current canvas-style transform with the provided matrix.

func (*Context) SetMiterLimit

func (r *Context) SetMiterLimit(limit float32)

SetMiterLimit sets the maximum allowed miter length ratio before falling back to a bevel join.

func (*Context) SetObjectTransform

func (r *Context) SetObjectTransform(x, y, size, rotation float32)

SetObjectTransform composes an object-local translation, uniform scale, and rotation with the current transform. Rotation is in radians.

func (*Context) SetShadowBlur

func (r *Context) SetShadowBlur(blur float32)

SetShadowBlur sets the blur radius used by subsequent shadow passes.

func (*Context) SetShadowColor

func (r *Context) SetShadowColor(color Color)

SetShadowColor sets the color used by subsequent shadow blur passes.

func (*Context) SetStrokeStyle

func (r *Context) SetStrokeStyle(color Color)

SetStrokeStyle sets the color used by Stroke.

func (*Context) SetTextAlign

func (r *Context) SetTextAlign(align TextAlign)

SetTextAlign sets the horizontal anchor used by FillText and StrokeText.

func (*Context) SetTextBaseline

func (r *Context) SetTextBaseline(baseline TextBaseline)

SetTextBaseline sets the vertical anchor used by FillText and StrokeText.

func (*Context) SetTransform

func (r *Context) SetTransform(a, b, c, d, e, f float32)

SetTransform replaces the current canvas-style transform with the specified affine matrix. The coefficients follow the HTML canvas convention: x' = a*x + c*y + e, y' = b*x + d*y + f.

func (*Context) SetTransformPolite

func (r *Context) SetTransformPolite(x, y, size, rotation float32)

SetTransformPolite is kept as a compatibility alias for SetObjectTransform.

func (*Context) Stroke

func (r *Context) Stroke()

Stroke strokes all current canvas-style subpaths with the current stroke style and line width.

func (*Context) StrokeText

func (r *Context) StrokeText(s string, x, y float32)

StrokeText draws an ASCII-oriented text stroke with the current stroke style and line width. x/y are interpreted using the current text align and baseline settings. If no font has been selected with SetFont, this is a no-op.

func (*Context) Transform

func (r *Context) Transform(a, b, c, d, e, f float32)

Transform post-multiplies the current canvas-style transform by the specified affine matrix.

func (*Context) TransformMatrix

func (r *Context) TransformMatrix(transform Matrix)

TransformMatrix post-multiplies the current canvas-style transform by the provided matrix.

type FontHandle

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

FontHandle is an opaque handle returned by LoadFont and consumed by Context.SetFont. A nil *FontHandle passed to SetFont selects the context's default font.

func LoadFont

func LoadFont(filePath string) (handle *FontHandle, err error)

LoadFont loads and parses a TrueType/OpenType font file and returns a reusable handle. Loaded handles are cached by normalized file path, so repeated calls for the same file are cheap and return the same handle. Passing an empty path loads FindSystemFont().

func LoadFontByName

func LoadFontByName(name string) (handle *FontHandle, err error)

func (*FontHandle) Path

func (h *FontHandle) Path() string

Path returns the normalized file path that was loaded for this font handle.

type FontWeight

type FontWeight int
const (
	FontWeightThin       FontWeight = 100
	FontWeightExtraLight FontWeight = 200
	FontWeightLight      FontWeight = 300
	FontWeightRegular    FontWeight = 400
	FontWeightNormal                = FontWeightRegular
	FontWeightMedium     FontWeight = 500
	FontWeightSemiBold   FontWeight = 600
	FontWeightBold       FontWeight = 700
	FontWeightExtraBold  FontWeight = 800
	FontWeightBlack      FontWeight = 900
)

type ImageEffect

type ImageEffect int
const (
	ImageEffectNone ImageEffect = iota
	ImageEffectElectric
)

type ImageShader

type ImageShader[T any] struct {
	// contains filtered or unexported fields
}

func NewImageShader

func NewImageShader[T any](ctx *Context, desc ImageShaderDescriptor, uniforms T) (shader *ImageShader[T], err error)

NewImageShader compiles a shader program and creates one typed shader instance. Prefer NewImageShaderProgram when many objects share the same WGSL.

func (*ImageShader[T]) Release

func (s *ImageShader[T]) Release()

Release frees the GPU resources associated with the shader instance. It does not affect the program, but the instance will no longer be usable.

func (*ImageShader[T]) SetUniforms

func (s *ImageShader[T]) SetUniforms(uniforms T) (err error)

SetUniforms updates the uniform buffer with new values. The shader instance must have been created with a compatible uniform type T.

type ImageShaderBinding

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

type ImageShaderDescriptor

type ImageShaderDescriptor struct {
	Label string
	WGSL  string
}

type ImageShaderProgram

type ImageShaderProgram[T any] struct {
	// contains filtered or unexported fields
}

func NewImageShaderProgram

func NewImageShaderProgram[T any](ctx *Context, desc ImageShaderDescriptor) (program *ImageShaderProgram[T], err error)

NewImageShaderProgram compiles a full WGSL image shader program that can be shared by many shader instances. The WGSL source is used exactly as provided. It must define compatible vs_main and fs_main entry points. Group 0 is reserved for the image sampler/texture. Group 1 binding 0 is the typed uniform block T.

func (*ImageShaderProgram[T]) NewInstance

func (p *ImageShaderProgram[T]) NewInstance(uniforms T) (shader *ImageShader[T], err error)

NewInstance creates a new shader instance with the given uniform values. The instance shares the program's pipeline and layout, but has its own uniform buffer and bind group.

func (*ImageShaderProgram[T]) Release

func (p *ImageShaderProgram[T]) Release()

Release frees the GPU resources associated with the shader program. It does not affect any shader instances, but they will no longer be usable.

type LineCap

type LineCap int
const (
	LineCapButt LineCap = iota
	LineCapRound
	LineCapSquare
)

type LineJoin

type LineJoin int
const (
	LineJoinMiter LineJoin = iota
	LineJoinRound
	LineJoinBevel
)

type Matrix

type Matrix struct {
	A float32
	B float32
	C float32
	D float32
	E float32
	F float32
}

func IdentityMatrix

func IdentityMatrix() Matrix

IdentityMatrix returns an identity affine transform.

func NewTransformMatrix

func NewTransformMatrix(x, y, scaleX, scaleY, rotation float32) Matrix

NewTransformMatrix returns a translation/rotation/scale affine transform.

func NewUniformTransformMatrix

func NewUniformTransformMatrix(x, y, scale, rotation float32) Matrix

NewUniformTransformMatrix returns a translation/rotation/uniform-scale affine transform.

func (Matrix) Apply

func (m Matrix) Apply(x, y float32) Point

Apply transforms a point using the affine matrix.

func (Matrix) Mul

func (m Matrix) Mul(next Matrix) Matrix

Mul composes two affine transforms using the HTML canvas convention current = current * next.

type OffscreenCanvas

type OffscreenCanvas struct {
	Width  int
	Height int
	// contains filtered or unexported fields
}

func NewOffscreenCanvas

func NewOffscreenCanvas(device *wgpu.Device, width, height int, formats ...gputypes.TextureFormat) (canvas *OffscreenCanvas, err error)

NewOffscreenCanvas creates a GPU-backed render target that can vend a frame-ready 2D context. If no format is supplied, RGBA8Unorm is used.

func (*OffscreenCanvas) Flush

func (c *OffscreenCanvas) Flush(clearColor *gputypes.Color) (err error)

Flush submits the current offscreen frame to the canvas texture.

func (*OffscreenCanvas) Format

func (*OffscreenCanvas) GetContext

func (c *OffscreenCanvas) GetContext() (ctx *Context, err error)

GetContext returns the canvas's drawing context and starts a new frame sized to the canvas.

func (*OffscreenCanvas) Image

func (c *OffscreenCanvas) Image(name string) *gimage.Image

Image returns a gimage.Image view over the offscreen canvas texture so it can be used with DrawImage. The returned image shares the canvas's GPU resources and must not be released independently.

func (*OffscreenCanvas) Release

func (c *OffscreenCanvas) Release()

func (*OffscreenCanvas) Sampler

func (c *OffscreenCanvas) Sampler() *wgpu.Sampler

func (*OffscreenCanvas) Texture

func (c *OffscreenCanvas) Texture() *wgpu.Texture

func (*OffscreenCanvas) View

func (c *OffscreenCanvas) View() *wgpu.TextureView

type Point

type Point struct {
	X float32
	Y float32
}

type TextAlign

type TextAlign int
const (
	TextAlignLeft TextAlign = iota
	TextAlignCenter
	TextAlignRight
)

type TextBaseline

type TextBaseline int
const (
	TextBaselineAlphabetic TextBaseline = iota
	TextBaselineTop
	TextBaselineMiddle
	TextBaselineBottom
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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