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
- Variables
- func ParseColor(css string) color.RGBA
- func RegisterFont(cache *SharedCache, family string, weight int, italic bool, data []byte, ...) error
- func RegisterIcon(cache *SharedCache, name string, svgData []byte, size float32) error
- func RegisteredFamilies() []string
- type Context
- func (c *Context) Arc(x, y, r, startAngle, endAngle float32, anticlockwise bool)
- func (c *Context) ArcTo(x1, y1, x2, y2, r float32)
- func (c *Context) BeginFrame()
- func (c *Context) BeginPath()
- func (c *Context) BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32)
- func (c *Context) ClearRect(x, y, w, h float32)
- func (c *Context) Clip()
- func (c *Context) ClosePath()
- func (c *Context) DrawIcon(name string, x, y, size float32, col color.RGBA)
- func (c *Context) DrawImage(src rl.Texture2D, dx, dy float32)
- func (c *Context) DrawImageCropped(src rl.Texture2D, srcRect, dst rl.Rectangle)
- func (c *Context) DrawImageOffscreen(src *Context, dst rl.Rectangle)
- func (c *Context) DrawImageOffscreenCropped(src *Context, srcRect, dst rl.Rectangle)
- func (c *Context) DrawImageOffscreenRounded(src *Context, dst rl.Rectangle, r float32)
- func (c *Context) DrawImageRounded(src rl.Texture2D, dst rl.Rectangle, r float32)
- func (c *Context) DrawImageRoundedCropped(src rl.Texture2D, srcRect, dst rl.Rectangle, r float32)
- func (c *Context) DrawImageScaled(src rl.Texture2D, dst rl.Rectangle)
- func (c *Context) EndFrame()
- func (c *Context) Fill()
- func (c *Context) FillCircle(x, y, r float32)
- func (c *Context) FillRect(x, y, w, h float32)
- func (c *Context) FillRoundRect(x, y, w, h, r float32)
- func (c *Context) FillRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)
- func (c *Context) FillRoundRectTop(x, y, w, h, r float32)
- func (c *Context) FillText(text string, x, y float32)
- func (c *Context) Height() int32
- func (c *Context) LineTo(x, y float32)
- func (c *Context) MeasureText(text string) float32
- func (c *Context) MoveTo(x, y float32)
- func (c *Context) Rect(x, y, w, h float32)
- func (c *Context) ResetTransform()
- func (c *Context) Restore()
- func (c *Context) RoundRect(x, y, w, h, r float32)
- func (c *Context) Save()
- func (c *Context) Scale(x, y float32)
- func (c *Context) SetAntialias(on bool)
- func (c *Context) SetDirection(s string)
- func (c *Context) SetFillColor(col color.RGBA)
- func (c *Context) SetFillStyle(css string)
- func (c *Context) SetFont(css string)
- func (c *Context) SetGlobalAlpha(a float32)
- func (c *Context) SetImageSmoothingEnabled(b bool)
- func (c *Context) SetLineCap(s string)
- func (c *Context) SetLineDash(segments []float32)
- func (c *Context) SetLineDashOffset(offset float32)
- func (c *Context) SetLineJoin(s string)
- func (c *Context) SetLineWidth(w float32)
- func (c *Context) SetMaskBackground(css string)
- func (c *Context) SetMaskBackgroundColor(col color.RGBA)
- func (c *Context) SetShadowBlur(b float32)
- func (c *Context) SetShadowColor(css string)
- func (c *Context) SetShadowOffsetX(x float32)
- func (c *Context) SetShadowOffsetY(y float32)
- func (c *Context) SetStrokeColor(col color.RGBA)
- func (c *Context) SetStrokeStyle(css string)
- func (c *Context) SetTextAlign(s string)
- func (c *Context) SetTextBaseline(s string)
- func (c *Context) SetTransform(a, b, cc, d, e, f float32)
- func (c *Context) Stroke()
- func (c *Context) StrokeCircle(x, y, r float32)
- func (c *Context) StrokeRect(x, y, w, h float32)
- func (c *Context) StrokeRoundRect(x, y, w, h, r float32)
- func (c *Context) StrokeRoundRectGradient(x, y, w, h, r float32, top, bottom color.RGBA)
- func (c *Context) StrokeRoundRectTop(x, y, w, h, r float32)
- func (c *Context) Texture() rl.Texture2D
- func (c *Context) Translate(x, y float32)
- func (c *Context) Unload()
- func (c *Context) Width() int32
- type FontKey
- type SharedCache
Constants ¶
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.
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 ¶
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.
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 ¶
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 ¶
Arc adds an arc segment. x, y: centre; r: radius; startAngle, endAngle: radians; anticlockwise: direction. Matches ctx.arc() exactly.
func (*Context) ArcTo ¶
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) BezierCurveTo ¶
BezierCurveTo adds a cubic Bézier segment. Matches ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y).
func (*Context) ClearRect ¶
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) DrawIcon ¶
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 ¶
DrawImage draws an entire texture at the given position. Equivalent to ctx.drawImage(src, dx, dy) in JavaScript.
func (*Context) DrawImageCropped ¶
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 ¶
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 ¶
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 ¶
DrawImageOffscreenRounded blits an off-screen Context onto this one with corners of radius r, the right way up.
func (*Context) DrawImageRounded ¶
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 ¶
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 ¶
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 ¶
FillCircle fills a full circle with the current fill style. Equivalent to: BeginPath(); Arc(x,y,r,0,2π,false); Fill()
func (*Context) FillRect ¶
FillRect fills an axis-aligned rectangle with the current fill style. Matches ctx.fillRect(x, y, w, h) in JavaScript.
func (*Context) FillRoundRect ¶
FillRoundRect fills a rounded rectangle with the current fill style. Equivalent to: BeginPath(); RoundRect(x,y,w,h,r); Fill()
func (*Context) FillRoundRectGradient ¶
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 ¶
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 ¶
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) MeasureText ¶
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) 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 ¶
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) SetAntialias ¶
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 ¶
SetDirection sets the text direction: "ltr" or "rtl". Used for RTL markdown rendering in joxel.
func (*Context) SetFillColor ¶
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 ¶
SetFillStyle sets the fill colour from a CSS colour string. Cached after first parse. Matches ctx.fillStyle = "..." in JavaScript.
func (*Context) SetFont ¶
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 ¶
SetGlobalAlpha sets the global alpha multiplier (0.0–1.0). Applied on top of any alpha embedded in fill/stroke colours.
func (*Context) SetImageSmoothingEnabled ¶
SetImageSmoothingEnabled controls bilinear filtering on DrawImage calls. When false, nearest-neighbour sampling is used.
func (*Context) SetLineCap ¶
SetLineCap sets the line cap style: "butt", "round", "square".
func (*Context) SetLineDash ¶
SetLineDash sets the dash pattern. An empty slice clears the dash. Matches ctx.setLineDash([...]) in JavaScript.
func (*Context) SetLineDashOffset ¶
SetLineDashOffset sets the phase offset for the dash pattern.
func (*Context) SetLineJoin ¶
SetLineJoin sets the line join style: "miter", "round", "bevel".
func (*Context) SetLineWidth ¶
SetLineWidth sets the stroke line width in pixels.
func (*Context) SetMaskBackground ¶
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 ¶
SetMaskBackgroundColor sets the colour that the corners of a rounded clip are painted with, from a colour value. See SetMaskBackground.
func (*Context) SetShadowBlur ¶
SetShadowBlur sets the shadow blur radius in pixels.
func (*Context) SetShadowColor ¶
SetShadowColor sets the shadow colour from a CSS colour string.
func (*Context) SetShadowOffsetX ¶
SetShadowOffsetX sets the horizontal shadow offset.
func (*Context) SetShadowOffsetY ¶
SetShadowOffsetY sets the vertical shadow offset.
func (*Context) SetStrokeColor ¶
SetStrokeColor sets the stroke colour from a colour value.
func (*Context) SetStrokeStyle ¶
SetStrokeStyle sets the stroke colour from a CSS colour string. Cached after first parse. Matches ctx.strokeStyle = "..." in JavaScript.
func (*Context) SetTextAlign ¶
SetTextAlign sets horizontal text alignment. Accepts "left", "center", "right". Matches ctx.textAlign = "..." in JavaScript.
func (*Context) SetTextBaseline ¶
SetTextBaseline sets the vertical text baseline. Accepts "alphabetic", "top", "middle", "bottom", "hanging", "ideographic".
func (*Context) SetTransform ¶
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 ¶
StrokeCircle strokes a full circle with the current stroke style.
func (*Context) StrokeRect ¶
StrokeRect strokes an axis-aligned rectangle with the current stroke style. Matches ctx.strokeRect(x, y, w, h) in JavaScript.
func (*Context) StrokeRoundRect ¶
StrokeRoundRect strokes a rounded rectangle with the current stroke style. Equivalent to: BeginPath(); RoundRect(x,y,w,h,r); Stroke()
func (*Context) StrokeRoundRectGradient ¶
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 ¶
StrokeRoundRectTop strokes a rectangle rounded only at the top two corners.
func (*Context) Texture ¶
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.
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 (*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.
|
| 
