raycanvas

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 13 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

raycanvas

v0.3.1 — work in progress

A Go package that mirrors the HTML5 CanvasRenderingContext2D API, backed by raylib-go for GPU rendering and fogleman/gg for CPU-side precision work (blur, anti-aliased curves, clip masks).

The goal is to let code written against the browser canvas API port to Go with minimal structural changes — same draw calls, same state model, same coordinate conventions.


Requirements

  • Go 1.25 or later
  • raylib system dependencies (X11/Wayland on Linux, standard on macOS/Windows)
    • Ubuntu: apt install libwayland-dev libxkbcommon-dev libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl1-mesa-dev

Quick start

import (
    rl "github.com/gen2brain/raylib-go/raylib"
    rc "github.com/ha1tch/raycanvas"
    "github.com/ha1tch/raycanvas/fonts"
)

func main() {
    cache := rc.NewSharedCache()
    ctx   := rc.SetupWindow(960, 640, "My App", cache)
    defer rl.CloseWindow()
    defer cache.Unload()
    rl.SetTargetFPS(60)

    // Register TTF fonts after SetupWindow (GPU must be ready)
    fonts.Register(cache)  // embeds Inter + Fira Code

    for !rl.WindowShouldClose() {
        ctx.BeginFrame()

        ctx.SetFillStyle("#1e1e2e")
        ctx.FillRect(0, 0, 960, 640)

        ctx.SetShadowColor("rgba(0,0,0,0.5)")
        ctx.SetShadowBlur(12)
        ctx.SetShadowOffsetY(4)
        ctx.SetFillStyle("#cba6f7")
        ctx.FillRoundRect(100, 100, 200, 120, 9)
        ctx.SetShadowColor("transparent")
        ctx.SetShadowBlur(0)
        ctx.SetShadowOffsetY(0)

        ctx.SetFont("700 13px inter")
        ctx.SetFillStyle("#1e1e2e")
        ctx.SetTextAlign("center")
        ctx.SetTextBaseline("middle")
        ctx.FillText("Hello raycanvas", 200, 160)

        ctx.EndFrame()
    }
}

Important: SetupWindow must be called before any GPU resource allocation — font registration, icon registration, off-screen contexts. It calls rl.SetConfigFlags(rl.FlagMsaa4xHint) and rl.InitWindow in the correct order.


API surface

State
ctx.Save()
ctx.Restore()
ctx.SetFillStyle(css string)
ctx.SetStrokeStyle(css string)
ctx.SetLineWidth(w float32)
ctx.SetGlobalAlpha(a float32)
ctx.SetFont(css string)           // e.g. "700 13px inter"
ctx.SetTextAlign(s string)        // "left" | "center" | "right"
ctx.SetTextBaseline(s string)     // "alphabetic" | "top" | "middle" | "bottom"
ctx.SetLineDash(segments []float32)
ctx.SetLineDashOffset(offset float32)
ctx.SetLineCap(s string)          // "butt" | "round" | "square"
ctx.SetLineJoin(s string)         // "miter" | "round" | "bevel"
ctx.SetImageSmoothingEnabled(b bool)
Transform
ctx.Translate(x, y float32)
ctx.Scale(x, y float32)
ctx.ResetTransform()
ctx.SetTransform(a, b, c, d, e, f float32)
Shadow
ctx.SetShadowColor(css string)
ctx.SetShadowBlur(b float32)
ctx.SetShadowOffsetX(x float32)
ctx.SetShadowOffsetY(y float32)

Shadow is applied to FillRect, FillRoundRect, FillCircle, and FillText. The blur pipeline renders the shape in fogleman/gg, applies Gaussian blur, uploads to a Texture2D, and caches by (color, blur, geometry). Text shadow is an offset draw (no blur), matching browser text-shadow behaviour.

Path
ctx.BeginPath()
ctx.ClosePath()
ctx.MoveTo(x, y float32)
ctx.LineTo(x, y float32)
ctx.Arc(x, y, r, startAngle, endAngle float32, anticlockwise bool)
ctx.ArcTo(x1, y1, x2, y2, r float32)
ctx.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32)
ctx.Rect(x, y, w, h float32)
ctx.RoundRect(x, y, w, h, r float32)
ctx.Fill()
ctx.Stroke()
ctx.Clip()
Convenience primitives

These bypass tessellation and dispatch directly to raylib — use these in preference to the path API for common shapes:

ctx.FillRect(x, y, w, h float32)
ctx.StrokeRect(x, y, w, h float32)
ctx.ClearRect(x, y, w, h float32)
ctx.FillRoundRect(x, y, w, h, r float32)
ctx.StrokeRoundRect(x, y, w, h, r float32)
ctx.FillRoundRectTop(x, y, w, h, r float32)  // rounded top corners only
ctx.StrokeRoundRectTop(x, y, w, h, r float32)
ctx.FillCircle(x, y, r float32)
ctx.StrokeCircle(x, y, r float32)

// A colour running from the top edge to the bottom edge, alpha included
ctx.FillRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)
ctx.StrokeRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)

Rounded rectangles are stepped at the corners unless the window has multisampling (SetupWindow asks for 4x). In a window opened some other way, turn on the soft edge:

ctx.SetAntialias(true)  // rounded fills, strokes, images and clip corners get a one-pixel soft edge
Text
ctx.FillText(text string, x, y float32)
ctx.MeasureText(text string) float32  // returns width
Images and off-screen
ctx.DrawImage(src rl.Texture2D, dx, dy float32)
ctx.DrawImageScaled(src rl.Texture2D, dst rl.Rectangle)
ctx.DrawImageCropped(src rl.Texture2D, srcRect, dst rl.Rectangle)
ctx.DrawImageOffscreen(src *rc.Context, dst rl.Rectangle)
ctx.DrawImageOffscreenCropped(src *rc.Context, srcRect, dst rl.Rectangle)

// With round corners. The corners are geometry, not paint: what lies
// behind them is left alone, whatever it is.
ctx.DrawImageRounded(src rl.Texture2D, dst rl.Rectangle, r float32)
ctx.DrawImageRoundedCropped(src rl.Texture2D, srcRect, dst rl.Rectangle, r float32)
ctx.DrawImageOffscreenRounded(src *rc.Context, dst rl.Rectangle, r float32)

// Off-screen context (backed by RenderTexture2D)
offscreen := rc.NewOffscreen(width, height int32, cache *rc.SharedCache)
defer offscreen.Unload()
tex := offscreen.Texture()  // rl.Texture2D for use in DrawImage*

Font system

Fonts are baked into atlas textures at specific pixel sizes. The atlas is selected at draw time so the font renders at exactly its baked resolution — no bilinear scaling.

// Register a TTF font (after SetupWindow)
data, _ := os.ReadFile("Inter-Regular.ttf")
rc.RegisterFont(cache, "inter", 400, false, data, nil)
// sizes defaults to []float32{8, 9, 10, 11, 12, 13, 14}

// Use in SetFont
ctx.SetFont("400 12px inter")
ctx.SetFont("700 13px inter")
ctx.SetFont("13px fira")

// Debug registered families
fmt.Println(rc.RegisteredFamilies())

Family names are normalised: "Fira Code" → "fira", "Inter" → "inter", "system-ui" → "inter". Font fallback: if the requested weight/style is not registered, the library tries the regular variant, then raylib's built-in 8×8 bitmap font.

The examples/internal/fonts package embeds Inter (400/500/600/700) and Fira Code (400/700) and can be imported directly:

import "github.com/ha1tch/raycanvas/examples/internal/fonts"
fonts.Register(cache)

Icons

SVG icons are rasterised at startup via oksvg + rasterx, pre-baked white-on-transparent, and tinted at draw time:

rc.RegisterIcon(cache, "close", closeSVGBytes, 14)
ctx.DrawIcon("close", x, y, 14, strokeColor)

Clip

Rectangular clips use rl.BeginScissorMode with intersection tracking across Save/Restore levels (max observed depth: 3).

Rounded-rect clips use a corner-overdraw technique: content is drawn normally inside the scissor bounding box, then the four corners outside the rounding are painted over in the background colour on Restore. This requires knowing the background colour, which is taken when Clip is called:

ctx.SetMaskBackground("#1e1e2e")  // optional — falls back to current fillStyle
ctx.Save()
ctx.BeginPath()
ctx.RoundRect(x, y, w, h, 9)
ctx.Clip()
// ... draw clipped content ...
ctx.Restore()  // corner caps applied here

Over anything that is not one solid colour, draw the content into an off-screen context and place it with DrawImageOffscreenRounded instead.


Bézier curves

Cubic Bézier strokes are rendered anti-aliased via gg, cached as Texture2D keyed on (p0, cp1, cp2, p1, lineWidth). Color and alpha are applied as a DrawTexturePro tint so animated opacity changes don't bust the cache.

Limitation: the Bézier cache is bounded at 1024 entries with FIFO eviction (no UnloadTexture on eviction — see Known Issues). If curve endpoints change continuously (draggable links), the cache fills quickly. LRU eviction is a planned improvement.


Examples

Build and run any example with make <name>, or build all with make build-examples.

Example What it demonstrates
basic FillRect, StrokeRect, globalAlpha, save/restore, RoundRect

basic example | text | Font variants, MeasureText, textAlign/textBaseline, word-wrap | | paths | Arc, ArcTo, LineDash, nested clip, animated arc sweep | | curves | BezierCurveTo with glow+stroke+pulse pattern |

curves example | grid | Spreadsheet: zoom transform, nested clip, headers, selection | | zui | Infinite canvas ZUI: pan/zoom, card drag, drop shadow, four themes | | shadows | Drop shadow, coloured glow, text shadow, blur depth |

shadows example

| icons | SVG icon registration: shevo icons, original icons, light/dark theme comparison |

icons example


Known issues and limitations

Path fill: no holes, no self-crossing outlines

Fill() cuts each sub-path into triangles by ear clipping, so outlines with notches (an L, a U, a star) fill correctly. A path whose sub-paths are meant as holes in one another, or an outline that crosses itself, is not filled by a winding rule as a browser would: each sub-path is filled on its own.

roundRect clip uses corner overdraw

The rounded-rect clip implementation paints over the corners with the background colour rather than performing true alpha masking. This means:

  • The background colour must be solid and known in advance (SetMaskBackground or current fillStyle)
  • Content behind the clipped region must be a solid colour
  • Semi-transparent backgrounds produce visible corner artefacts

The rounded image calls (DrawImageRounded, DrawImageOffscreenRounded) do not have this limit.

Text shadow is offset-only

SetShadowBlur has no effect on FillText. Text shadow is rendered as a second draw at the shadow offset in the shadow colour. Browser text-shadow with blur requires rasterising the glyph outlines through gg, which is not yet implemented.

Font baseline approximation

The alphabetic baseline correction (0.75 * fontSize) is empirically tuned for Inter and Fira Code at 8–14px. At larger or smaller sizes, or with other fonts, text may sit slightly higher or lower than the equivalent browser canvas rendering.

Stroke placement without the soft edge

Without SetAntialias, StrokeRoundRect draws its line outside the rectangle and StrokeRect inside it, which are raylib's conventions; a canvas centres the line on the outline. With SetAntialias(true), StrokeRoundRect is centred.

No rotation

SetTransform accepts a full matrix, but rectangles, images, clips and shadows read only its scale and translation.

No gradient or pattern support

createLinearGradient, createRadialGradient, and createPattern are not implemented. The canvas API surface implemented matches the subset actually used in the target application.

No quadratic curves

quadraticCurveTo is not implemented. Only cubic Bézier (bezierCurveTo) is supported.


Dependencies

Package Role
github.com/gen2brain/raylib-go/raylib v0.60.0 GPU rendering, window, input
github.com/fogleman/gg v1.3.0 CPU precision rendering: shadow blur, Bézier AA, clip masks
github.com/srwiley/oksvg SVG path parsing for icon rasterisation
github.com/srwiley/rasterx SVG rasterisation backend

All four are pure Go apart from raylib itself. They come with the package whether or not the importing program uses shadows or icons.


Build system

make help            — list all targets
make build           — type-check the library
make build-examples  — compile all examples to bin/
make basic           — build and run the basic example
make zui             — build and run the ZUI example
make test            — run the tests (the drawing ones need a display)
make fmt-check       — fail if any file is not gofmt-clean
make release V=0.3.0 — cut a versioned release (checks CHANGELOG)
make patch V=0.2.2-patched01 — checkpoint zip, no CHANGELOG check
make package         — quick zip of current state
make clean           — remove bin/ and zips

Licence

Copyright (c) 2026 haitch
Licensed under the Apache License, Version 2.0
https://www.apache.org/licenses/LICENSE-2.0

Documentation

Overview

Package raycanvas provides a 2D drawing API that mirrors the HTML5 CanvasRenderingContext2D interface, backed by raylib-go for GPU rendering.

It is designed as the rendering substrate for porting Shevo perspectives (joxel, quag, dekk) from JavaScript to Go, allowing ported code to use familiar canvas idioms (BeginPath, FillRect, Arc, BezierCurveTo, etc.) while raylib handles the GPU layer.

Architecture

Rendering is split into two tiers:

  • Hot path (GPU, every frame): FillRect, StrokeRect, FillText, path fill/stroke, image blit. All dispatched to raylib primitives.

  • Cold path (CPU, cached): Shadow blur, arbitrary-path clip masks, SVG icon rasterisation. Computed once via fogleman/gg and cached as Texture2D values. Never executed inside the frame loop.

Typical usage

cache := raycanvas.NewSharedCache()
defer cache.Unload()

// Register fonts (call after rl.InitWindow)
firaData, _ := os.ReadFile("FiraCode-Regular.ttf")
raycanvas.RegisterFont(cache, "fira", 400, false, firaData, nil)

// Register icons
raycanvas.RegisterIcon(cache, "undo", undoSVG, 14)

ctx := raycanvas.NewContext(int32(w), int32(h), cache)

for !rl.WindowShouldClose() {
    ctx.BeginFrame()
    ctx.SetFillStyle("#1e1e2e")
    ctx.FillRect(0, 0, float32(w), float32(h))
    // ... draw calls ...
    ctx.EndFrame()
}

Type conventions

All geometry parameters use float32. Color parameters use color.RGBA (the standard library type, also used natively by raylib-go). CSS color strings and font strings are accepted as Go strings and cached after the first parse.

See ARCHITECTURE.md for the full design rationale and constraint documentation.

Index

Constants

View Source
const (
	// ShadowCacheMax is the maximum number of entries in the shadow+bezier
	// texture cache. With integer-snapped blur values, the set of distinct
	// animated shadow textures is bounded by the blur range (typically 1–30),
	// so 1024 is large enough that eviction is rare in practice.
	ShadowCacheMax = 1024

	// ColorCacheMax is the maximum number of CSS color strings cached.
	// Shevo has ~60 distinct strings per theme; 256 is a generous ceiling.
	ColorCacheMax = 256
)

Cache size constants.

View Source
const TessellationSteps = 32

TessellationSteps controls the number of line segments used to approximate curved path segments (arcs, arcTo). 32 is sufficient for arcs up to ~200px radius at typical screen resolutions. Increase for very large arcs.

Variables

View Source
var DefaultCodepoints []rune // nil = raylib default set (ASCII + basic Latin)

DefaultCodepoints is the Unicode range baked into every atlas. Covers Latin, Latin-1 Supplement, and Latin Extended-A — sufficient for all shevo UI chrome and typical cell content. Extend for non-Latin scripts.

View Source
var DefaultFontSizes = []float32{8, 9, 10, 11, 12, 13, 14}

DefaultFontSizes lists the pixel sizes baked for every registered font. Matches all sizes observed in shevo source. Add to this list if new sizes are introduced in ported code.

Functions

func ParseColor

func ParseColor(css string) color.RGBA

ParseColor parses a CSS color string and returns color.RGBA. This is the public version of resolveColor for use outside a Context — useful when passing colours to DrawIcon or other calls that take color.RGBA directly.

func RegisterFont

func RegisterFont(cache *SharedCache, family string, weight int, italic bool, data []byte, sizes []float32) error

RegisterFont registers a TTF font variant and bakes atlas textures for all requested sizes. Must be called after rl.InitWindow and before any draw calls.

family  — canonical family name: "fira", "inter", "georgia", "system"
weight  — numeric weight: 400, 500, 600, 700
italic  — true for italic variant
data    — raw TTF file bytes (embed with //go:embed or read from disk)
sizes   — pixel sizes to bake; pass nil to use DefaultFontSizes

Weights used in shevo:

  • Fira Code: 400 (regular), 700 (bold). No italic variant exists.
  • Inter: 400, 500, 600, 700; italic variants for 400 and 700.
  • Georgia: 400, 700.

func RegisterIcon

func RegisterIcon(cache *SharedCache, name string, svgData []byte, size float32) error

RegisterIcon parses an SVG and rasterises it at the given size, storing the result as a GPU Texture2D in the cache.

Icons are pre-rasterised with white-on-transparent so they can be tinted at draw time via DrawTexturePro's tint parameter. This matches how shevo uses currentColor: the caller passes the current stroke or fill colour as the tint.

Must be called after rl.InitWindow and before any draw calls.

name    — identifier used in DrawIcon calls
svgData — raw SVG bytes (embed with //go:embed or read from disk)
size    — target render size in pixels (icons are square)

func RegisteredFamilies

func RegisteredFamilies() []string

RegisteredFamilies returns the canonical family names currently registered in the font registry. Useful for debugging font name mismatches — the API accepts these names (case-insensitive after normalisation) in SetFont calls.

Types

type Context

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

Context is a stateful 2D drawing context backed by raylib. It mirrors the HTML5 CanvasRenderingContext2D API as closely as practical.

Two kinds of Context exist:

  • Screen context: draws directly to the framebuffer. Create with NewContext.
  • Off-screen context: draws into a RenderTexture2D. Create with NewOffscreen.

A single SharedCache should be created per application and passed to all Context constructors. It holds all GPU-resident cached resources (fonts, icons, shadow textures).

func NewContext

func NewContext(width, height int32, cache *SharedCache) *Context

NewContext creates a screen-space Context that draws to the raylib framebuffer. Call BeginFrame before drawing and EndFrame after. width and height should match the window dimensions.

func NewOffscreen

func NewOffscreen(width, height int32, cache *SharedCache) *Context

NewOffscreen creates an off-screen Context backed by a RenderTexture2D. The texture is allocated immediately; call Unload when done.

Important: RenderTexture2D has Y-axis flipped relative to the screen. When blitting via DrawImageCropped, pass srcRect with negative Height to flip. This is handled internally by DrawImage* methods.

func SetupWindow

func SetupWindow(width, height int32, title string, cache *SharedCache) *Context

SetupWindow configures raylib flags for best visual quality and then initialises the window. Call this instead of rl.InitWindow directly.

Currently enables:

  • FlagMsaa4xHint: 4× multisample antialiasing for all GPU-rendered shapes (DrawRectangleRounded, DrawCircleV, DrawSplineLinear, etc.). This flag must be set before the OpenGL context is created, so it cannot be applied after InitWindow. SetupWindow handles the ordering.

Required call order — GPU resources cannot be allocated before InitWindow:

cache := raycanvas.NewSharedCache()
ctx   := raycanvas.SetupWindow(800, 600, "My App", cache)  // InitWindow happens here
defer rl.CloseWindow()
defer cache.Unload()
rl.SetTargetFPS(60)
raycanvas.RegisterFont(cache, ...)  // safe: window is open
raycanvas.RegisterIcon(cache, ...)  // safe: window is open

func (*Context) Arc

func (c *Context) Arc(x, y, r, startAngle, endAngle float32, anticlockwise bool)

Arc adds an arc segment. x, y: centre; r: radius; startAngle, endAngle: radians; anticlockwise: direction. Matches ctx.arc() exactly.

func (*Context) ArcTo

func (c *Context) ArcTo(x1, y1, x2, y2, r float32)

ArcTo adds an arc-to segment (rounded corner primitive). Matches ctx.arcTo(x1, y1, x2, y2, radius). x/y = first control point, x2/y2 = second control point, r = radius.

func (*Context) BeginFrame

func (c *Context) BeginFrame()

BeginFrame sets up the drawing surface for a new frame. For screen contexts: wraps rl.BeginDrawing. For off-screen contexts: wraps rl.BeginTextureMode. Call exactly once per frame before any draw calls.

EnableSmoothLines is called every frame — it enables GL_LINE_SMOOTH, OpenGL's native line antialiasing, which applies to all line primitives (DrawLineEx, DrawSplineLinear, DrawCircleLinesV, etc.) at no per-draw cost.

func (*Context) BeginPath

func (c *Context) BeginPath()

func (*Context) BezierCurveTo

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

BezierCurveTo adds a cubic Bézier segment. Matches ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y).

func (*Context) ClearRect

func (c *Context) ClearRect(x, y, w, h float32)

ClearRect clears a rectangle to transparent black, effectively erasing it. Matches ctx.clearRect(x, y, w, h) in JavaScript.

func (*Context) Clip

func (c *Context) Clip()

Clip uses the current path as a clipping region, intersecting with any existing clip. The current path is consumed (cleared after this call), matching HTML5 canvas behaviour.

Implementation dispatch:

  • If the current path is a single axis-aligned rect: scissor mode.
  • If the current path is a roundRect: scissor mode for the bounding box, and when the clip is closed by Restore the four corners are painted over in a background colour. This only looks like a rounded clip over a solid colour: the mask background (SetMaskBackground) or, failing that, the fill style in force when Clip is called. Over anything else (a picture, a gradient, another window's content) draw the content to an off-screen Context and place it with DrawImageOffscreenRounded, or use DrawImageRounded for a texture: those round the geometry itself.
  • All other paths: bounding-box scissor only (sufficient for shevo).

func (*Context) ClosePath

func (c *Context) ClosePath()

func (*Context) DrawIcon

func (c *Context) DrawIcon(name string, x, y, size float32, col color.RGBA)

DrawIcon draws a named icon at the given position and size, tinted with col. col replaces "currentColor" — pass the current stroke or fill colour. size controls the rendered square dimensions; the icon is scaled to fit. Matches the pattern ctx.drawImage(iconTexture, x, y, size, size).

func (*Context) DrawImage

func (c *Context) DrawImage(src rl.Texture2D, dx, dy float32)

DrawImage draws an entire texture at the given position. Equivalent to ctx.drawImage(src, dx, dy) in JavaScript.

func (*Context) DrawImageCropped

func (c *Context) DrawImageCropped(src rl.Texture2D, srcRect, dst rl.Rectangle)

DrawImageCropped draws a sub-rectangle of src scaled to fill dst. Equivalent to ctx.drawImage(src, sx, sy, sw, sh, dx, dy, dw, dh) in JavaScript.

RenderTexture2D Y-flip: when src comes from an off-screen Context (.Texture()), pass srcRect with negative Height to flip the image right-way-up:

srcRect := rl.Rectangle{X: 0, Y: 0, Width: float32(w), Height: -float32(h)}

This is handled automatically when the source is an off-screen Context — use DrawImageOffscreen for that case.

func (*Context) DrawImageOffscreen

func (c *Context) DrawImageOffscreen(src *Context, dst rl.Rectangle)

DrawImageOffscreen blits an off-screen Context onto this Context. Handles the RenderTexture2D Y-flip automatically. dst specifies the destination rectangle in this Context's local space.

func (*Context) DrawImageOffscreenCropped

func (c *Context) DrawImageOffscreenCropped(src *Context, srcRect, dst rl.Rectangle)

DrawImageOffscreenCropped blits a sub-rectangle of an off-screen Context. srcRect is in the source Context's local space (before Y-flip correction).

func (*Context) DrawImageOffscreenRounded

func (c *Context) DrawImageOffscreenRounded(src *Context, dst rl.Rectangle, r float32)

DrawImageOffscreenRounded blits an off-screen Context onto this one with corners of radius r, the right way up.

func (*Context) DrawImageRounded

func (c *Context) DrawImageRounded(src rl.Texture2D, dst rl.Rectangle, r float32)

DrawImageRounded draws an entire texture scaled to fill dst, with corners of radius r. The corners are part of the geometry: nothing is drawn outside them, so the image may lie over anything, not only a solid colour. This is what a rounded clip cannot give (see Clip).

func (*Context) DrawImageRoundedCropped

func (c *Context) DrawImageRoundedCropped(src rl.Texture2D, srcRect, dst rl.Rectangle, r float32)

DrawImageRoundedCropped draws a sub-rectangle of src scaled to fill dst, with corners of radius r. As with DrawImageCropped, a negative srcRect.Height flips the image, which a render texture needs.

func (*Context) DrawImageScaled

func (c *Context) DrawImageScaled(src rl.Texture2D, dst rl.Rectangle)

DrawImageScaled draws an entire texture scaled to fill dst. Equivalent to ctx.drawImage(src, dx, dy, dw, dh) in JavaScript.

func (*Context) EndFrame

func (c *Context) EndFrame()

EndFrame finalises the current frame. For screen contexts: wraps rl.EndDrawing. For off-screen contexts: wraps rl.EndTextureMode.

func (*Context) Fill

func (c *Context) Fill()

Fill fills the current path with the current fill style. Matches ctx.fill() in JavaScript. The path is cleared after this call.

func (*Context) FillCircle

func (c *Context) FillCircle(x, y, r float32)

FillCircle fills a full circle with the current fill style. Equivalent to: BeginPath(); Arc(x,y,r,0,2π,false); Fill()

func (*Context) FillRect

func (c *Context) FillRect(x, y, w, h float32)

FillRect fills an axis-aligned rectangle with the current fill style. Matches ctx.fillRect(x, y, w, h) in JavaScript.

func (*Context) FillRoundRect

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

FillRoundRect fills a rounded rectangle with the current fill style. Equivalent to: BeginPath(); RoundRect(x,y,w,h,r); Fill()

func (*Context) FillRoundRectGradient

func (c *Context) FillRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)

FillRoundRectGradient fills a rounded rectangle with a colour that runs from top at its upper edge to bottom at its lower edge. The alpha of the two colours runs with them, so a panel can be see-through at the top and solid at the bottom. The fill style is not used. It is always a mesh, with a soft edge when antialiasing is on, and it casts no shadow.

func (*Context) FillRoundRectTop

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

FillRoundRectTop fills a rectangle rounded only at the top two corners. This is the rrTop primitive from quag — used for title bars drawn over a card body. Equivalent to a rounded rect with the bottom squared off. Implemented as two stacked raylib calls to avoid path tessellation.

func (*Context) FillText

func (c *Context) FillText(text string, x, y float32)

FillText draws text at the given position using the current font and fill style. Matches ctx.fillText(text, x, y) in JavaScript.

textAlign and textBaseline are applied to compute the final draw position.

func (*Context) Height

func (c *Context) Height() int32

Height returns the height of the drawing surface in pixels.

func (*Context) LineTo

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

func (*Context) MeasureText

func (c *Context) MeasureText(text string) float32

MeasureText returns the rendered width of text in the current font. Matches ctx.measureText(text).width in JavaScript. Returns 0 if no font is set.

func (*Context) MoveTo

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

func (*Context) Rect

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

Rect adds a closed rectangle sub-path. Matches ctx.rect(x, y, w, h).

func (*Context) ResetTransform

func (c *Context) ResetTransform()

ResetTransform resets the current transform to the identity matrix.

func (*Context) Restore

func (c *Context) Restore()

Restore pops the drawing state from the stack. Matches ctx.restore() in JavaScript. Re-applies the clip from the restored state. If a roundRect masked region was open, composites it before restoring.

func (*Context) RoundRect

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

RoundRect adds a closed rounded-rectangle sub-path. r is a pixel radius (NOT a 0–1 ratio; that conversion happens inside draw.go when dispatching to rl.DrawRectangleRounded). Matches ctx.roundRect(x, y, w, h, r).

func (*Context) Save

func (c *Context) Save()

Save pushes the current drawing state onto the stack. Matches ctx.save() in JavaScript.

func (*Context) Scale

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

Scale applies a scale to the current transform.

func (*Context) SetAntialias

func (c *Context) SetAntialias(on bool)

SetAntialias turns the soft edge of rounded rectangles and rounded images on or off. It is off by default, which draws exactly what earlier versions drew and relies on the window's multisampling (SetupWindow asks for 4x). Turn it on in a window opened without multisampling, where the corners would otherwise be stepped. It belongs to the context, not to the state that Save and Restore keep.

func (*Context) SetDirection

func (c *Context) SetDirection(s string)

SetDirection sets the text direction: "ltr" or "rtl". Used for RTL markdown rendering in joxel.

func (*Context) SetFillColor

func (c *Context) SetFillColor(col color.RGBA)

SetFillColor sets the fill colour from a colour value rather than a CSS string, for callers that already hold one (a theme, say). The alpha in the value is kept and globalAlpha still applies on top of it.

func (*Context) SetFillStyle

func (c *Context) SetFillStyle(css string)

SetFillStyle sets the fill colour from a CSS colour string. Cached after first parse. Matches ctx.fillStyle = "..." in JavaScript.

func (*Context) SetFont

func (c *Context) SetFont(css string)

SetFont sets the current font from a CSS font string. Example: "italic 700 13px Inter", "500 9px 'Fira Code'". Cached after first parse. Matches ctx.font = "..." in JavaScript.

func (*Context) SetGlobalAlpha

func (c *Context) SetGlobalAlpha(a float32)

SetGlobalAlpha sets the global alpha multiplier (0.0–1.0). Applied on top of any alpha embedded in fill/stroke colours.

func (*Context) SetImageSmoothingEnabled

func (c *Context) SetImageSmoothingEnabled(b bool)

SetImageSmoothingEnabled controls bilinear filtering on DrawImage calls. When false, nearest-neighbour sampling is used.

func (*Context) SetLineCap

func (c *Context) SetLineCap(s string)

SetLineCap sets the line cap style: "butt", "round", "square".

func (*Context) SetLineDash

func (c *Context) SetLineDash(segments []float32)

SetLineDash sets the dash pattern. An empty slice clears the dash. Matches ctx.setLineDash([...]) in JavaScript.

func (*Context) SetLineDashOffset

func (c *Context) SetLineDashOffset(offset float32)

SetLineDashOffset sets the phase offset for the dash pattern.

func (*Context) SetLineJoin

func (c *Context) SetLineJoin(s string)

SetLineJoin sets the line join style: "miter", "round", "bevel".

func (*Context) SetLineWidth

func (c *Context) SetLineWidth(w float32)

SetLineWidth sets the stroke line width in pixels.

func (*Context) SetMaskBackground

func (c *Context) SetMaskBackground(css string)

SetMaskBackground sets the background colour used for roundRect clip corner overdraw. Call this before Save()/RoundRect()/Clip() when the region behind the clipped content is a known solid colour. Defaults to transparent black.

func (*Context) SetMaskBackgroundColor

func (c *Context) SetMaskBackgroundColor(col color.RGBA)

SetMaskBackgroundColor sets the colour that the corners of a rounded clip are painted with, from a colour value. See SetMaskBackground.

func (*Context) SetShadowBlur

func (c *Context) SetShadowBlur(b float32)

SetShadowBlur sets the shadow blur radius in pixels.

func (*Context) SetShadowColor

func (c *Context) SetShadowColor(css string)

SetShadowColor sets the shadow colour from a CSS colour string.

func (*Context) SetShadowOffsetX

func (c *Context) SetShadowOffsetX(x float32)

SetShadowOffsetX sets the horizontal shadow offset.

func (*Context) SetShadowOffsetY

func (c *Context) SetShadowOffsetY(y float32)

SetShadowOffsetY sets the vertical shadow offset.

func (*Context) SetStrokeColor

func (c *Context) SetStrokeColor(col color.RGBA)

SetStrokeColor sets the stroke colour from a colour value.

func (*Context) SetStrokeStyle

func (c *Context) SetStrokeStyle(css string)

SetStrokeStyle sets the stroke colour from a CSS colour string. Cached after first parse. Matches ctx.strokeStyle = "..." in JavaScript.

func (*Context) SetTextAlign

func (c *Context) SetTextAlign(s string)

SetTextAlign sets horizontal text alignment. Accepts "left", "center", "right". Matches ctx.textAlign = "..." in JavaScript.

func (*Context) SetTextBaseline

func (c *Context) SetTextBaseline(s string)

SetTextBaseline sets the vertical text baseline. Accepts "alphabetic", "top", "middle", "bottom", "hanging", "ideographic".

func (*Context) SetTransform

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

SetTransform replaces the current transform with the given matrix, using the same (a,b,c,d,e,f) parameter order as the HTML5 canvas API.

func (*Context) Stroke

func (c *Context) Stroke()

Stroke strokes the current path with the current stroke style. Matches ctx.stroke() in JavaScript. The path is cleared after this call.

func (*Context) StrokeCircle

func (c *Context) StrokeCircle(x, y, r float32)

StrokeCircle strokes a full circle with the current stroke style.

func (*Context) StrokeRect

func (c *Context) StrokeRect(x, y, w, h float32)

StrokeRect strokes an axis-aligned rectangle with the current stroke style. Matches ctx.strokeRect(x, y, w, h) in JavaScript.

func (*Context) StrokeRoundRect

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

StrokeRoundRect strokes a rounded rectangle with the current stroke style. Equivalent to: BeginPath(); RoundRect(x,y,w,h,r); Stroke()

func (*Context) StrokeRoundRectGradient

func (c *Context) StrokeRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)

StrokeRoundRectGradient strokes a rounded rectangle with the current line width, centred on the outline, in a colour that runs from top at the rectangle's upper edge to bottom at its lower edge, as FillRoundRectGradient does. The stroke style is not used.

func (*Context) StrokeRoundRectTop

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

StrokeRoundRectTop strokes a rectangle rounded only at the top two corners.

func (*Context) Texture

func (c *Context) Texture() rl.Texture2D

Texture returns the underlying GPU texture for this off-screen context. Use this as the source argument to DrawImage* calls. Panics if called on a screen context.

func (*Context) Translate

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

Translate applies a translation to the current transform.

func (*Context) Unload

func (c *Context) Unload()

Unload releases the GPU resources held by an off-screen context. Must be called before the raylib window is closed. No-op on a screen context.

func (*Context) Width

func (c *Context) Width() int32

Width returns the width of the drawing surface in pixels.

type FontKey

type FontKey struct {
	Family string  // "fira", "inter", "georgia", "system"
	Size   float32 // exact pixel size — must match draw call fontSize
	Weight int     // 400=regular, 500=medium, 600=semibold, 700=bold
	Italic bool
}

FontKey uniquely identifies a rasterised font atlas. A separate rl.Font (atlas texture) is baked for each unique FontKey.

Critical rule: bake size == draw size. When DrawTextEx is called with fontSize == font.BaseSize, raylib renders directly from the atlas with no scaling — maximum sharpness. We therefore bake at every pixel size used.

Sizes used in shevo: 8, 9, 10, 11, 12, 13, 14.

type SharedCache

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

SharedCache holds all pre-computed GPU resources. A single instance is shared across all Context values within an application. All methods are safe for concurrent use during asset loading; frame-loop access is read-only after startup and requires no locking.

func NewSharedCache

func NewSharedCache() *SharedCache

NewSharedCache allocates an empty cache.

func (*SharedCache) Unload

func (sc *SharedCache) Unload()

Unload releases all GPU resources held by the cache. Call once, after the raylib window is still open but before CloseWindow.

Directories

Path Synopsis
fonts module
pkg
version
Package version exposes the raycanvas library version.
Package version exposes the raycanvas library version.

Jump to

Keyboard shortcuts

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