webcanvas

package module
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 11 Imported by: 2 modules, 2 packages

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

webcanvas

CI Go Reference Go Report Card

Runs a go-widgets scene in a browser tab, on a plain <canvas>: no compositor, no SharedArrayBuffer, no cross-origin isolation, nothing on the far end. It blits an RGBA framebuffer into the canvas and routes DOM pointer and keyboard events back into the scene.

It carries no widget logic of its own. An application implements a small interface and hands it to Run:

//go:build js && wasm

package main

import "github.com/go-widgets/webcanvas"

func main() { webcanvas.Run("screen", myScene()) }

Several canvases on one page. Run is the single-canvas entry point and never returns. Mount(canvas js.Value, app App) *Surface puts a scene on any <canvas> and returns at once; Run is Mount, Focus, park. Every listener belongs to its surface, so two surfaces never see each other's input:

  • Keys are heard by the surface that has focus, and only by it. The canvas is made focusable (tabindex="0" unless the page set one), so a click or Tab focuses it, and Surface.Focus() does it from code. Before, the keyboard listeners were on window, and every canvas on the page received every key. Run focuses its canvas, so a one-canvas page still types from the start; click elsewhere on the page and the keys stop, as they do for any focusable element.
  • The wheel goes to the surface under the pointer. A Scroller always takes it (preventDefault), as before. A scene that implements ScrollConsumer, Scroll(x, y, dx, dy int) (repaint, consumed bool), takes it only when it used it: with consumed == false the page scrolls under the canvas, so an editor among prose does not trap the wheel. The listener is registered {passive: false}: per the WHATWG DOM Standard, preventDefault does nothing while a listener's passive flag is set, and wheel listeners default to passive only on window, document, its root element and body, not on a canvas.
  • Surface.Close() removes every listener, timer and animation frame the surface installed, and is idempotent; the other surfaces carry on. A Presenter has no teardown of its own.

Surface.Canvas() is the canvas. The key target is the canvas for now; it is kept in one place so that an accessibility mirror can take it over later without changing this API (#21). browsertest/ mounts two surfaces among prose in headless Chrome: a key typed after a click reaches only that surface, a real wheel over a scene that does not consume it scrolls the page, one over a scene that does leaves it, and after Close every addEventListener is matched by a removeEventListener.

App is Size, Draw(buf []byte), and one method per kind of event, each reporting whether the scene changed so a repaint can be skipped when nothing did. A scene may also implement Ticker, Animator, Resizer or Scroller to be told about time, animation, a resized canvas or the wheel, and ModifierAware to be told the state of Ctrl, Shift, Alt and Meta before every pointer, keyboard and wheel event -- without it Ctrl+A, Cmd+A and Alt+A all reach KeyDown as "a", and a Shift-click is a click.

HiDPI. A Resizer scene that also implements PixelRatioAware renders at the display's device pixels: the canvas backing store becomes its CSS box × window.devicePixelRatio, the scene is told the ratio (a go-widgets scene forwards it to toolkit.SetMetricScale) and gets device pixels in Resize, and both follow browser zoom and moves between displays (a matchMedia resolution query, as MDN's Window.devicePixelRatio shows). Without it a Retina display upscales a 1× bitmap: blurred, stair-stepped text. The page gives the canvas its CSS size (width: 100vw; height: 100vh).

A scene whose content changes while nobody touches it -- a fetch that completes, a message that arrives -- implements RepaintWith(request func()) (RepaintAware). request asks for one frame, from any goroutine, coalesced into the next animation frame. Without it such a scene shows its first frame until the next click. browsertest/ checks this in headless Chrome, and fails when the hook is removed.

Key positions and releases. A scene that implements KeyCode(code string) (KeyCodeAware) is told each keyboard event's physical key, the DOM's KeyboardEvent.code ("KeyA", "ArrowUp", "ShiftLeft"), just before the event, the way ModifierAware is told the modifiers. The key ("a", "A", "é") is what was typed. Its code is where the key is, "not affected by the current keyboard layout or modifier state" (W3C UI Events), which is what a game, or a guest that expects key positions, needs. A code longer than 32 bytes is passed as "". A scene that implements KeyUp(key string) bool (KeyUpper) also gets key releases, with the same key values and the code and modifiers first. Run installs the keyup listener only for such a scene. Scenes that implement neither see exactly the events they did before. browsertest/ types Shift+A and checks char A KeyA shift=true and up A KeyA shift=true.

Images the browser already holds. A scene can show frames a GPU rendered into an ImageBitmap, a video, or another canvas without copying their pixels through Draw's buffer: it implements Layers() []Layer (Layered). Each layer is an opaque Image (NewImage(jsValue)), a rectangle in canvas pixels (device pixels for a PixelRatioAware scene) and an optional alpha. After every Draw, Run calls drawImage for each layer, in order, scaled into its rectangle with high-quality smoothing.

Bounds and safety:

  • At most 64 layers are drawn per frame.
  • A layer with no image, an empty rectangle, a rectangle entirely off the canvas, or an alpha that is not in [0, 1] is skipped.
  • Each layer is drawn under its own recover net, so a closed ImageBitmap, which makes drawImage throw, costs only that layer.
  • The images remain the scene's: Run never closes or keeps them.

browsertest/ draws a closed bitmap, then a 2×2 green bitmap scaled into a 4×4 corner, and reads the pixels back.

Repainting only what changed. Without help, every frame is Draw of the whole scene, a copy of the whole framebuffer into the browser and a putImageData of the whole canvas, even when one caret blinked or only a guest's frame in a Layer is new. A scene that knows what it changed implements DrawDamaged(buf []byte) []Rect (DamageDrawer), and the host then copies and puts only those rectangles (putImageData's dirty-rectangle arguments). It is the contract go-widgets/window's DamageRenderer gives a desktop host, in the browser's terms: the scene repaints just what changed into a framebuffer that persists between frames and returns the rectangles it repainted, as toolkit.Rect (webcanvas.Rect is the same type); an empty result means nothing changed and nothing is put. Draw still runs for the first frame and after every resize. A scene that does not implement it behaves exactly as before.

Layers are always drawn again (the image behind a handle can change without the handle doing so), but they cost no scene repaint and no putImageData: a frame with no damage and opaque layers puts nothing. A layer that moved, shrank or went has its old rectangle put back from the scene buffer; a layer with Alpha < 1, or whose image may have transparent pixels (Opaque false, the default), has the scene put back under it on every frame, so it never stacks on its own previous frame. Opaque: true promises every pixel is opaque and is what lets a still guest frame cost nothing.

Measured under GOOS=js in node, 1280×800, a fake 2D context (so the browser's own putImageData time, which only widens the gap, is not in it), five interleaved rounds:

frame before (whole) after
one 120×40 widget changes 2.89 ms 0.031 ms
no damage, one opaque 800×600 layer 2.90 ms 0.021 ms

present_test.go checks the canvas against a full repaint, pixel for pixel, through moving, fading and translucent layers; browsertest/ counts putImageData calls and their rectangles in Chrome. The webcanvas/gpu presenter redraws the scene on the GPU every frame and does not use it.

Windows over content the host draws as DOM. A scene may draw some of its content as real DOM rather than into the canvas — a page of text the browser lays out and the reader can select, a video, an <iframe> — and still paint windows of its own over it. It cannot, by default:

A DOM element is unconditionally above a canvas. The canvas and the element are siblings in the page, so a window painted into the canvas cannot come forward over one, however the application stacks it internally.

There is no z-index that fixes this and no drawing order that avoids it. The only way a canvas-painted window appears over DOM content is for the host to punch a hole in the DOM content where the window is. ClipPath([]Overlay, dpr) builds that hole as a CSS clip-path; the host applies it to the element holding its DOM content, and clip-path: none when the string is empty.

  • Coordinates are canvas pixels, the same space Draw paints and Layer is placed in; dpr converts them to the CSS pixels a path() reads.
  • Each Overlay carries the corner radius of the window drawn there. A square hole behind a rounded window cuts the content out at the corners while the canvas leaves them transparent, and the void between the two reads as black notches around the window.
  • The path is the outer ring plus one closed subpath per hole, filled evenodd. A single polygon threading from the ring in to each hole and back has that journey drawn, and leaves a wedge cut out of the content.
  • At most 64 holes per frame; empty rectangles punch nothing and do not use up the budget; a radius past half the shorter side is clamped; a dpr that is not a positive number is taken as 1 rather than producing NaN coordinates, which a browser rejects — and a rejected clip path is no clip path.

Measured in the go-tex playground, which is where it comes from: dragging its find-and-replace panel over the rendered page sliced the panel off at the page's edge until the hole existed.

Accessibility

A <canvas> is one opaque image to a screen reader. A scene that implements A11yAware, A11yNodes() []A11yNode, gets an accessibility mirror: a DOM subtree beside the canvas that says in ARIA what the scene paints. Mount and Run build it; nothing else changes for a scene that does not implement it.

func (s *scene) A11yNodes() []webcanvas.A11yNode {
	return []webcanvas.A11yNode{
		{Key: "Button#0", Role: "button", Name: "Save", X: 10, Y: 20, W: 80, H: 30},
		{Key: "@cell3", Role: "textbox", Name: "Go cell 3", Value: src, Multiline: true, X: 150, Y: 20, W: 200, H: 80},
	}
}
  • Nodes are in reading order, in surface pixels. Key is stable across frames (toolkit's A11yNode.Key); the mirror diffs by it, so an unchanged key keeps the same DOM element and a screen reader's virtual cursor is not reset on every frame.
  • Roles: button (a native <button>), checkbox, switch and radio (aria-checked), slider, progressbar, meter and spinbutton (aria-valuemin/max/now/valuetext), text, textbox (role=textbox, aria-multiline, aria-readonly), status, alert and log, and any other WAI-ARIA role name. Disabled is aria-disabled.
  • Hidden visually, not from assistive technology: the root is clipped (clip-path: inset(50%), overflow: hidden), never display: none, visibility: hidden or aria-hidden, and has pointer-events: none, so the mouse still reaches the canvas.
  • Focus: the mirror element of the focused node holds real DOM focus, and the mirror root is the surface's key target.
  • Activation: a click on a mirror element (a screen reader's "activate") is replayed as a press and release at the node's centre; so is a focus that assistive technology moves onto a focusable node.
  • Announcements: status and log text that appears or changes is written to one persistent polite live region, alert text to an assertive one. Both exist, empty, before the first announcement.
  • Cost: a changed tree is published at most every 200 ms, and a change refused as too soon is deferred, never dropped. An unchanged tree costs a 64-bit signature. A resize and a change of the focused node are never held back. Surface.Refresh() draws a frame and updates the mirror for a host that changed the scene from outside.
  • Key activation: Enter or Space on a focused mirror element activates exactly once. The mirror cancels the keydown (UI Events: a canceled keydown dispatches no click), hands the key to the scene, and replays one click only if the scene did not consume it. A native click that still follows a handled key (detail 0, within 500 ms) is dropped.
  • Node cap: a mirror never holds more than 5,000 nodes, whatever the scene returns. Above that, the tree is cut to the 5,000 that matter: a status node first ("Accessibility view truncated: showing 4999 of N items", announced like any status), the focused node and its subtree (at most half the budget), then the first nodes in reading order. Larger documents need the paged mirror planned in #21 (W4).
  • Untrusted text: names, values and roles may come from the user (a notebook from anyone). They reach the DOM only through textContent and setAttribute; there is no innerHTML. A role that is not lowercase letters and hyphens is dropped.

Measured in headless Chrome, 2,000 nodes (browsertest, go test -v -run TestMirrorCost): building the tree 70 ms, one changed node 6.5 ms, an unchanged frame 0.5 ms, every node moved 36 ms, every node reordered 119 ms.

The text layer

A scene that also implements TextInputHost (TextInputFor(key string) textinput.Client, from go-widgets/textinput) gets a text layer for each textbox node it publishes (#21, W3). The layer replaces the plain div role=textbox: it is the widget's only accessibility element, its editing host and the text the browser's find and selection see.

  • Structure: one div per model line, placed at the model's line position (InputRect), the runes of each line put on the toolkit's cell grid by letter-spacing from a measured width table (planLine). Text and caret are transparent, so the canvas still paints the glyphs. white-space: pre, tab-size: 1. The browser paints the selection and the find matches (::selection, ::search-text).
  • Editing: contenteditable="plaintext-only" only while the layer has focus, so a selection dragged between prose and code is an ordinary one. keydown goes through routeKey: navigation and modified keys to App.KeyDown, printable keys not at all; text arrives through beforeinput (routeInput) and is applied once with ReplaceInput. A composition runs in place in the DOM line and reaches the model through SetMarkedInput (compositionEdit); compositionend commits and rewrites the line. selectionchange calls SetInputSelection. An input the layer did not understand goes through textinput.Reconcile.
  • Bounds: 32 layers per surface, 20,000 lines per layer, 4,000 UTF-16 units per line. Text reaches the DOM through textContent only.
  • Tests: the pure part is at 100% coverage. browsertest/ checks, in headless Chrome, a positioning error under 0.05 px at device pixel ratios 1 and 2, one textbox in the AX tree whose value is the code and no second copy, window.find, a selection from prose into code and from code into prose, one "a" for one keystroke, Input.imeSetComposition and its commit, and the bound. TEXTLAYER_COST=1 go test -run TestTextLayerKeystrokeCost -v prints the keystroke cost table.
  • Not checked: that a Ctrl+F match is visible over the canvas in Chrome, Safari and Firefox (it needs a headed browser), and the canvas still paints its own selection band.

The clipboard

A canvas has no clipboard of its own. A widget toolkit that keeps one in memory (go-widgets/toolkit's default) copies and pastes only inside the page. NewClipboard() connects it to the browser's clipboard. Install it once at startup:

toolkit.SetClipboard(webcanvas.NewClipboard())
  • Copy: the text also goes to navigator.clipboard.writeText. The copy runs inside the keydown that asked for it, which is the user activation the Clipboard API requires. A refused write keeps the copy inside the page.
  • Paste: the only synchronous read that needs no permission prompt is a paste event's clipboardData. So Ctrl+V and Cmd+V (Shift allowed, Alt not) are held at keydown and not prevented. The browser fires paste on the focused canvas, the bridge takes its text, and only then is the key delivered: the widget's own paste reads what the user copied elsewhere. Some shortcuts fire no paste event on a canvas: Chromium's Ctrl+Shift+V, which is a terminal's paste on Linux, is "paste and match style" and does not (the wasmcontainers playground's e2e showed it). For those, the bridge reads navigator.clipboard.readText() instead, which the browser may ask the user to allow once, and then delivers the key. If the read is refused too, the key is delivered anyway, as before the bridge. The key a scene sees does not change, only when it arrives: a terminal that sends Ctrl+V as ^V still does.
  • The bound: a paste keeps at most 1 MiB, cut on a rune boundary.
  • The Edit menu: a paste from the browser's Edit menu refreshes the text without pressing a key.

Checked in headless Chrome (browsertest/clipboard_test.go): the key arrives once, after the paste event, carrying its text; with no paste event it arrives once, from the fallback; a copy calls writeText. The paste event in that test is dispatched by the page, because headless Chrome offers no way to choose what its clipboard holds. Not checked by a test: a real Cmd+V in a headed Chrome, Firefox or Safari, in particular whether Safari fires paste on a focused, non-editable canvas. Where it does not, the fallback keeps the old behaviour.

On the GPU

RunWith(id, app, presenter) hands the canvas to a Presenter instead of painting Draw's buffer with putImageData. Package webcanvas/gpu is a presenter that draws on the GPU through WebGPU:

webcanvas.RunWith("screen", app, gpu.New())
  • Which apps: one that also implements gpu.Painted, Paint(painter.Painter), which paints the whole frame as it would into a PixelPainter.
  • How: the app is recorded through go-widgets/gpupainter into a go-gfx/gpu2d list. gpu2d's WebGPU renderer draws it and copies the frame into the canvas texture on the GPU, so nothing passes through Go memory or putImageData.
  • Same pixels: TestThePresenterDrawsWhatDrawPaints holds the GPU frame to Draw's CPU frame byte for byte, before and after a resize. gpu2d's own test holds the canvas texture to that frame.
  • Choosing once: a canvas takes one kind of context for life, so the choice is made once, before the first frame. The presenter asks the canvas for its WebGPU context only after it has a device, a renderer and a surface. Any earlier failure leaves the canvas untouched, and Run paints through 2D as before; the presenter's Err says why. That covers a browser without WebGPU and an app that is not Painted.
  • Layered scenes: their images are drawn through the 2D context, so they are never offered to a presenter.
  • Resizing: the renderer is rebuilt at the new size, and the old one's memory is released.
  • Frames with no damage: a Painted app that also implements gpu.DamagePainted, PaintDamaged(painter.Painter) []Rect, reports what changed since its last call, as toolkit's scene.HostRoot.RenderDamaged does (minus the *toolkit.Theme, which webcanvas does not own: the app wraps it). An empty result means nothing changed, and the presenter neither records nor presents the frame. The first frame and the one after a resize are always whole. TestAFrameWithNoDamageIsSkipped holds the canvas to a full repaint after every frame and the draw and present counts to the damage; TestGPUPresenterSkipsFramesWithoutDamage counts the command buffers a frame sends in Chrome (an idle frame: none). On a 1024 × 768 grid of 1,200 cells an idle frame's two GPU submits go to none, and its recording from a median 122.9 µs (whole scene) to 11.4 ns, with 0 allocations in both (BenchmarkIdleFrame, Apple M4 Max, one core, 5 rounds at load below 3). An app without PaintDamaged is recorded and presented every frame, as before.
  • Frames with damage: the recording of a damaged frame is PaintDamaged's own, confined to the damage (so it must repaint the ground under it, as RenderDamaged does), and the renderer composites it over its persistent target, which holds the rest. With one cell of the 1,200 damaged, the list handed to the renderer goes from 2,401 instances to 2, and its recording from a median 133.2 µs (whole scene) to 129.9 ns (BenchmarkDamagedFrame, same machine and rounds; the one allocation, 32 B, is the damage list). The canvas texture itself cannot be the persistent one: per the WebGPU spec (section 21.2, GPUCanvasContext, the "Replace the drawing buffer" algorithm) the texture getCurrentTexture() returns after a presentation starts as transparent black, and TestTheWebGPUCanvasTextureDoesNotKeepItsContents measures the same in Chrome. So each presented frame still copies the whole target to the canvas, on the GPU.

Where this came from

It was internal/webcanvas inside go-widgets/gallery, where nothing outside that one module could import it. It is the same code, in a place a second application can reach — which is the point: the DOM plumbing exists once.

Testing

go test -covermode=set ./...

CI gates on exact 100% statement coverage, go vet, a cross-compile across the fleet's targets, and a js/wasm build.

What that coverage does and does not say. The interface, the scene contract and the event dispatch are covered. run_js.go — the DOM loop itself — is behind a js && wasm build tag and so is not part of the measured build at all: it compiles for the browser and is exercised by browsertest/, a real headless Chrome driven by chromedp (also mirror_js.go, the mirror's DOM glue; the mirror's decisions are in mirror.go and are covered). A gate that reports 100% while a file is invisible to it is worth saying out loud.

License

BSD-3-Clause — see LICENSE. Copyright the go-widgets/webcanvas authors.

Documentation

Index

Constants

View Source
const MaxLayers = 64

MaxLayers bounds the layers drawn per frame.

View Source
const MaxOverlays = 64

MaxOverlays bounds the holes punched per frame, as MaxLayers bounds the images drawn per frame. A clip path grows with every hole and is rebuilt whenever a window moves.

Variables

View Source
var PanicReporter = func(r any, stack []byte) {
	fmt.Fprintf(os.Stderr, "webcanvas: recovered panic in a handler: %v\n%s\n", r, stack)
}

PanicReporter logs a handler panic the [guard] net recovered. The wasm host swaps in a console.error reporter carrying the JS stack; the default writes to standard error so a native run — and the recover test — still surfaces it. It is a package var, not a const, precisely so run_js.go can replace it.

Functions

func ClipPath added in v0.8.0

func ClipPath(overlays []Overlay, dpr float64) string

ClipPath is the CSS clip-path that punches every overlay out of the element holding the host's DOM content: the outer ring, then one subpath per hole, filled evenodd. dpr converts the device-pixel geometry to the CSS-pixel user space a path() reads.

It returns "" when there is nothing to punch, which the caller applies as clip-path: none rather than as an empty path -- an empty path clips everything away.

⛔ TWO SUBPATHS PER HOLE, NOT ONE POLYGON. A single path threading from the outer ring in to each hole and back out again has that journey DRAWN, and it leaves a wedge cut out of the content. The outer box plus one closed subpath per hole, filled evenodd, is what cuts holes and nothing else.

Types

type A11yAware added in v0.11.0

type A11yAware interface {
	A11yNodes() []A11yNode
}

A11yAware is implemented by a scene that publishes an accessibility tree. The mirror reads A11yNodes after every frame it draws.

type A11yNode added in v0.11.0

type A11yNode struct {
	// Key is stable across frames for the same widget (toolkit.A11yNode.Key:
	// a path of "@<id>" or "<Type>#<n>" segments). Two nodes of one frame must
	// not share a Key; the mirror keeps the first. An unchanged Key keeps the
	// same DOM element, so the browser keeps the same node and a screen
	// reader's virtual cursor is not reset on every frame.
	Key string
	// Role, Name and Value are the ARIA role, the accessible name and the
	// current value (a textbox's text, "checked", "pressed", ...). They come
	// from the app and may be untrusted: the mirror only ever puts them in
	// textContent and attribute values.
	Role, Name, Value string
	// X, Y, W, H are the node's bounds in surface pixels.
	X, Y, W, H int
	// Focused: the widget holds toolkit focus, so its element holds DOM focus.
	Focused bool
	// Disabled, ReadOnly and Multiline map to aria-disabled, aria-readonly and
	// aria-multiline.
	Disabled, ReadOnly, Multiline bool
	// HasRange gates Min, Max and Now (aria-valuemin, -valuemax, -valuenow).
	HasRange      bool
	Min, Max, Now float64
}

A11yNode is one accessible element of a scene, in surface (device) pixels. It is the plain, dependency-free twin of toolkit.A11yNode: whoever owns the toolkit tree converts toolkit.WalkA11y into a slice of these, in reading order. Role names are WAI-ARIA 1.2 role names (toolkit.Role already uses them).

type Animator

type Animator interface {
	// AnimationStep advances the scene's animation by dt seconds of real elapsed
	// time and reports whether the scene now needs a repaint.
	AnimationStep(dt float64) (repaint bool)
}

Animator is an optional companion to App: a scene with time-varying content driven by a REAL wall clock (procedurally animated icons, say) implements it, and [Run] installs a requestAnimationFrame loop that hands it the elapsed dt between frames — in seconds — through AnimationStep. Unlike Ticker (a fixed cadence that always repaints), an Animator advances by the true frame delta and reports whether the frame changed anything, so Run repaints only when a pixel actually moved. A scene that implements neither installs no clock and repaints on input alone. The phase-advance logic lives in the scene (natively testable); only the rAF wiring is browser-side.

type App

type App interface {
	// Size returns the fixed pixel dimensions of the scene's surface. The host
	// sizes the canvas and allocates the framebuffer from it; it is read once,
	// at startup, so it must not change over the App's life.
	Size() (w, h int)

	// Draw paints the whole scene into buf, a width*height*4 RGBA byte slice
	// laid out exactly like an image.RGBA's Pix (row-major, 4 bytes/pixel).
	Draw(buf []byte)

	// Click delivers a primary (left) button press at (x, y). It begins a
	// gesture — a selection, a drag, a placement — that later Move/Release
	// calls advance and commit.
	Click(x, y int) bool

	// Move delivers a pointer move at (x, y). While a Click gesture is in
	// flight it is a drag tick; otherwise it is a hover.
	Move(x, y int) bool

	// Release delivers the primary button release at (x, y), committing any
	// in-flight gesture Click began.
	Release(x, y int) bool

	// Context delivers a secondary (right) button press at (x, y), typically
	// opening a context menu. The host suppresses the browser's own menu.
	Context(x, y int) bool

	// Char delivers a single printable character typed with no Ctrl/Meta/Alt
	// modifier — text input for a focused field.
	Char(s string) bool

	// KeyDown delivers a named key (Enter, Backspace, Delete, Arrow*, …) or a
	// modified key press, routed to the focused widget.
	KeyDown(s string) bool
}

App is a self-contained canvas scene. A host (the wasm [Run] loop, or a native test) owns the pixel buffer and the event source; the App owns the widgets. Every coordinate is in canvas-local pixels (top-left origin), the same space [Run] derives from the pointer event's position within the canvas' bounding rectangle.

Each event method reports whether the scene changed and therefore needs a repaint, so the host can skip a redraw when nothing moved. Draw is expected to fully paint the buffer (it is never given a dirty region).

type Clipboard added in v0.13.0

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

Clipboard is a text clipboard backed by the browser's. It has the method set of go-widgets/toolkit's Clipboard, so a host installs it with toolkit.SetClipboard(webcanvas.NewClipboard()). The zero value is an in-memory clipboard; NewClipboard (js/wasm) connects it to the browser and makes it the one paste shortcuts wait for.

func (*Clipboard) ClipboardText added in v0.13.0

func (c *Clipboard) ClipboardText() string

ClipboardText returns the current text: the last paste the browser delivered, or the last text set.

func (*Clipboard) SetClipboardText added in v0.13.0

func (c *Clipboard) SetClipboardText(s string)

SetClipboardText replaces the text and writes it to the browser's clipboard.

type DamageDrawer added in v0.15.0

type DamageDrawer interface {
	App
	DrawDamaged(buf []byte) []Rect
}

DamageDrawer is an optional companion to App: a scene that knows what its last frame changed implements it, and the host then copies and puts only those rectangles on the canvas instead of the whole framebuffer.

It is the browser's form of the contract go-widgets/window's DamageRenderer (RenderDamaged(p, th) []toolkit.Rect) gives a desktop host, with the same meaning: the scene repaints only what changed into a framebuffer that PERSISTS between frames, and returns the rectangles it repainted, in canvas pixels; an EMPTY result means nothing changed, and the host puts nothing. (toolkit.Surface.Damage differs: there nil means "everything", so it cannot say "nothing", which is the frame that costs least.) RenderDamaged itself does not fit: it is handed a painter.Painter and a *toolkit.Theme, while App.Draw gets a bare RGBA buffer and webcanvas owns no theme.

The host calls App.Draw (the whole scene) for the first frame and after every resize, then DrawDamaged. A change omitted from the result is a change the canvas never shows, so return every rectangle whose pixels differ from the previous frame; a scene that cannot tell leaves the interface off, or answers with a rectangle covering the canvas. It must also do the work the frame owes (draining a queue, say), as Draw does.

type Image added in v0.6.0

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

Image is a browser image the host can draw over the scene: an ImageBitmap, a <canvas>, an OffscreenCanvas, an <img> -- anything CanvasRenderingContext2D drawImage accepts. The scene holds it as an opaque handle: a syscall/js Value in the browser; in a native build or test any value, which the host never draws (there is no canvas to draw it on).

func NewImage added in v0.6.0

func NewImage(handle any) Image

NewImage wraps handle (a js.Value in the browser) as an Image.

func (Image) Handle added in v0.6.0

func (i Image) Handle() any

Handle is the value NewImage was given.

func (Image) IsZero added in v0.6.0

func (i Image) IsZero() bool

IsZero reports whether i holds nothing.

type KeyCodeAware added in v0.7.0

type KeyCodeAware interface {
	KeyCode(code string)
}

KeyCodeAware is an optional companion to App: a scene that implements it is told the physical key of every keyboard event -- the DOM's KeyboardEvent.code ("KeyA", "ArrowUp", "ShiftLeft") -- immediately before the event is delivered (Char, KeyDown, or KeyUp for a KeyUpper). The event's key ("a", "A", "é") is what was typed; its code is where on the keyboard it was, "not affected by the current keyboard layout or modifier state" (W3C UI Events, KeyboardEvent.code) -- what a game or a remote guest that expects key positions needs. A scene that does not implement it sees exactly the events it always did.

type KeyUpper added in v0.7.0

type KeyUpper interface {
	KeyUp(key string) bool
}

KeyUpper is an optional companion to App: a scene that implements it is told when a key is released (the DOM's keyup, which a user agent "MUST dispatch ... when a key is released"), with the same key value KeyDown and Char get. [Run] installs the keyup listener only for such a scene. KeyUp reports whether the scene changed.

type Layer added in v0.6.0

type Layer struct {
	Image      Image
	X, Y, W, H int
	// Alpha is the opacity in (0, 1]; 0 (the zero value) means opaque.
	Alpha float64
	// Opaque promises that every pixel of the image is opaque. With Alpha 1 the
	// layer then replaces what is under it, which lets a [DamageDrawer] scene
	// redraw the layer alone, without putting the scene's pixels back first.
	// Left false (an image may have transparent pixels), the host restores the
	// scene under the layer on every frame, which is always correct.
	Opaque bool
}

Layer is one image drawn over the scene after App.Draw, scaled into its rectangle. Coordinates are canvas pixels, the same space Draw paints: device pixels for a PixelRatioAware scene, so an image lands sharp at any ratio.

type Layered added in v0.6.0

type Layered interface {
	Layers() []Layer
}

Layered is an optional companion to App: a scene that shows images the browser already holds -- frames a GPU rendered into an ImageBitmap, a video -- implements it, rather than copying their pixels through Draw's buffer. After every Draw, [Run] calls Layers and draws each one, in order, with drawImage scaled into its rectangle (smoothing on, quality high). Each layer is drawn under its own recover net, so one unusable image (a closed ImageBitmap throws InvalidStateError) costs that layer only.

The images are the scene's: Run never closes or keeps them past the call. A scene that omits the interface draws exactly as before.

type ModifierAware added in v0.3.0

type ModifierAware interface {
	Modifiers(m Modifiers)
}

ModifierAware is an optional companion to App: a scene that implements it is told the modifier state immediately before every pointer, keyboard and wheel event is delivered. Without it a modified key reaches KeyDown as its bare name -- "a" for Ctrl+A, Cmd+A and Alt+A alike -- and a Shift-click is a click: a scene could not tell copy from select-all, nor extend a selection. A scene that does not implement it sees exactly the events it always did.

type Modifiers added in v0.3.0

type Modifiers struct {
	Ctrl, Shift, Alt, Meta bool
}

Modifiers is the state of the modifier keys when an event happened, as the DOM event reports it (ctrlKey, shiftKey, altKey, metaKey).

type Overlay added in v0.8.0

type Overlay struct {
	X, Y, W, H int
	// Radius is the corner radius of the window drawn here. ⛔ It matters: a
	// SQUARE hole behind a ROUNDED window cuts the DOM content out at the
	// corners while the canvas leaves them transparent, and the void between
	// the two reads as black notches around the window.
	Radius int
}

Overlay is one rectangle the CANVAS paints on top of content the host draws as DOM, carrying the corner radius of the window drawn there.

Coordinates are canvas pixels, the same space App.Draw paints and Layer is placed in: device pixels for a PixelRatioAware scene. Radius is in the same pixels; 0 is a square-cornered window.

type PixelRatioAware added in v0.5.0

type PixelRatioAware interface {
	SetPixelRatio(ratio float64)
}

PixelRatioAware is an optional companion to Resizer: a scene that can render at the display's device pixels implements it. [Run] then sizes the canvas backing store to the canvas' CSS box × window.devicePixelRatio, tells the scene the ratio before each Resize (which is handed device pixels), and re-does both when the ratio changes (browser zoom, a window moved to a display of another density). On a ratio-2 display the scene draws twice the pixels in each direction instead of a 1× bitmap the browser upscales into blocky, blurred text. A go-widgets scene typically forwards the ratio to toolkit.SetMetricScale, which scales every metric and re-renders the OpenType face.

The page must give the canvas its CSS size (e.g. width: 100vw; height: 100vh): the backing store no longer equals it. A scene that omits the interface keeps rendering at CSS pixels, unchanged.

type Rect added in v0.15.0

type Rect = painter.Rect

Rect is a rectangle in canvas pixels. It is painter.Rect, which is also toolkit.Rect: the type go-widgets/window's DamageRenderer and toolkit's Surface.Damage already use, so a scene reports damage in one vocabulary.

type RepaintAware added in v0.4.0

type RepaintAware interface {
	RepaintWith(request func())
}

RepaintAware is an optional companion to App: a scene whose content can change while nobody touches it -- a fetch that completes, a message that arrives -- and that therefore needs a frame no event will cause.

Before the first frame, [Run] hands it request. Calling request asks for one frame at the next animation frame; it is safe from any goroutine, returns at once, and coalesces: any number of calls before that frame is drawn give one frame. The scene does its pending work at the start of App.Draw -- for a go-widgets tree, draining an mvvm.Queue -- so the frame shows it.

type Resizer

type Resizer interface {
	// Resize relays out the scene to fit w×h device pixels and returns the pixel
	// size (rw, rh) it will render at — the size the host sizes the canvas and
	// framebuffer to.
	Resize(w, h int) (rw, rh int)
}

Resizer is an optional companion to App: a scene that can adapt its layout to a NEW surface size implements it, and [Run] installs a window "resize" listener (and fits the canvas to the viewport once at startup) that re-sizes the canvas and framebuffer, calls Resize, and repaints. A scene that omits it keeps the fixed App.Size forever — the pre-resize behaviour every existing demo relies on — so Run never installs the listener and the surface never changes.

Resize is handed the target pixel size (the canvas' laid-out client box) and returns the size it will actually render at: a scene may clamp to a sane minimum, and the host allocates the framebuffer from the RETURNED size, so the scene and the buffer can never disagree. The relayout logic lives in the scene (natively testable); only the DOM resize wiring is browser-side.

type ScrollConsumer added in v0.10.0

type ScrollConsumer interface {
	// Scroll delivers a wheel scroll of dy vertical and dx horizontal ROWS at
	// canvas-local (x, y). repaint: the scene changed. consumed: the scene used
	// the event, so the page must not scroll.
	Scroll(x, y, dx, dy int) (repaint, consumed bool)
}

ScrollConsumer is Scroller for a page that holds more than one canvas, or a canvas among prose: the scene says whether it USED the wheel. When consumed is false the host does not call preventDefault, so the page scrolls under the pointer as if the canvas were not there. A canvas editor that has no vertical scroll left to give, or whose pointer is over a part of the scene that does not scroll, returns (false, false).

Why "not calling preventDefault" is the whole mechanism (WHATWG DOM, https://dom.spec.whatwg.org/ §2.9 and §2.7): Event.preventDefault() sets the canceled flag only if the event's "in passive listener flag" is unset, and that flag is set while a listener whose "passive" is true runs. The "default passive value" is true for wheel, mousewheel, touchstart and touchmove only when the target is a Window, a Document, its document element or its body; for a <canvas> the default is false. A surface therefore registers its wheel listener with {passive: false}, so that preventDefault CAN cancel the scroll when the scene consumed the event, and simply does not call it when not.

A scene implements Scroller or ScrollConsumer, not both: the method name is shared. Scroller keeps its old meaning, the wheel is always consumed.

type Scroller

type Scroller interface {
	// Scroll delivers a wheel / trackpad scroll of dy vertical and dx horizontal
	// ROWS at canvas-local (x, y), and reports whether the scene needs a repaint.
	Scroll(x, y, dx, dy int) (repaint bool)
}

Scroller is an optional companion to App: a scene with a scrollable region (a docked list, an icon palette, an overflowing panel) implements it, and [Run] installs a "wheel" listener that translates the browser's WheelEvent into toolkit scroll ROWS and routes them — with the canvas-local pointer position, so the scene can hit-test which region the wheel is over — through Scroll. A scene that omits it installs no wheel listener, so the page keeps its default wheel behaviour and every existing demo (the widget gallery) is unchanged. A Scroller always takes the wheel (preventDefault); a scene that must let the page scroll when it does not use the wheel implements ScrollConsumer instead.

dx / dy are the horizontal / vertical scroll amounts in toolkit ROWS (already normalised from the event's deltaMode by [scrollRows]): positive dy scrolls down / forward, positive dx scrolls right. A scene typically forwards them to the widget under (x, y) as a [toolkit.Event] of kind EventScroll (Delta = dy, DeltaX = dx), which scrollable widgets clamp at both ends. Scroll reports whether the scene changed and therefore needs a repaint.

type TextInputHost added in v0.12.0

type TextInputHost interface {
	// TextInputFor returns the client of the text widget published under key
	// (the node's Key), or nil.
	TextInputFor(key string) textinput.Client
}

TextInputHost is implemented by a scene that has text widgets. The mirror asks it, for every node whose role is textbox, for the widget's text-input client; a nil answer leaves that node a plain <div role=textbox>.

type Ticker

type Ticker interface {
	// Tick advances one animation frame. Run repaints after every Tick.
	Tick()
}

Ticker is an optional companion to App: a scene that needs a steady animation clock (a toast countdown, a blinking caret) implements it, and [Run] installs a 60-Hz timer that calls Tick and repaints. A scene with no time-varying state omits it, and Run installs no timer, so it never repaints except in response to input.

Directories

Path Synopsis
browsertest module
Package gpu is a webcanvas.Presenter that draws on the GPU through WebGPU.
Package gpu is a webcanvas.Presenter that draws on the GPU through WebGPU.

Jump to

Keyboard shortcuts

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