Skip to content
Kite

WebAssembly: mount Kite on a browser canvas

Use backend/wasm instead of a terminal backend when the host is a web page. The screen is still measured in rows and columns. Keep your components portable; put syscall/js and canvas setup in a browser-specific entry point such as main_js.go.

The host must supply a real <canvas> with a 2D context. Because wasm.New and *wasm.Backend are guarded by //go:build js && wasm, put that build tag at the top of your browser entry point and compile with GOOS=js GOARCH=wasm:

//go:build js && wasm
package main
import (
"context"
"log"
"syscall/js"
"github.com/masterkeysrd/kite"
"github.com/masterkeysrd/kite/backend/wasm"
"github.com/masterkeysrd/kite/element"
)
func main() {
doc := js.Global().Get("document")
canvas := doc.Call("getElementById", "terminal")
b, err := wasm.New(
canvas,
wasm.WithSize(60, 18),
wasm.WithFont("monospace", 16),
)
if err != nil {
log.Print(err)
return
}
app := kite.New(b, kite.WithMouseMode(kite.MouseModeTrack))
app.Mount(element.Box("Hello, canvas!"))
if err := app.Run(context.Background()); err != nil {
log.Print(err)
}
}

WithSize sets the cell grid; WithFont, WithLineHeight, and WithPadding control its presentation. The canvas renderer batches contiguous dirty background and text runs per row to minimize WASM↔JS calls, and reads window.matchMedia("(prefers-color-scheme: dark)") to drive style.Query().ColorScheme(...) media queries. To mount Kitex instead of retained elements, use kitex.CreateRoot(app).Render(view) before Run.

From the directory containing the Go entry point, put these two files beside the host HTML (use -trimpath -ldflags="-s -w" to strip debug symbols for production builds):

Terminal window
GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o app.wasm .
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" .

Serve the files over HTTP. Load the runtime from the same Go installation that built the binary. This loader uses an array buffer, so it doesn’t depend on streaming compilation or a particular WASM response MIME type.

<canvas id="terminal" tabindex="0"></canvas>
<script src="./wasm_exec.js"></script>
<script type="module">
const go = new Go()
const response = await fetch('./app.wasm')
if (!response.ok) {
throw new Error(`WASM: ${response.status}`)
}
const bytes = await response.arrayBuffer()
const { instance } = await WebAssembly.instantiate(bytes, go.importObject)
await go.run(instance)
</script>

For an embedded view, retain a stop function in the host integration. On unmount, stop the engine with app.Stop() and let Run finish before discarding the canvas. Engine shutdown calls the backend’s Restore(); it removes browser event listeners, releases their Go callbacks, and closes input exactly once. If managing the backend directly, call b.Restore() yourself. Removing the canvas alone does not stop a running Go app. Mount a fresh backend for a new canvas.