Getting started
One package and one tag: there are no services to register and no stylesheet to link, because the package's Blazor initializer adds the canvas stylesheet by itself. Everything else - brushes, tools, saving and export - is plain C# on the component and its document.
Install
In a Blazor Web App the package belongs in the .Client project, so the component's assembly
is downloaded to the browser; the server project gets it transitively and prerenders the same pages.
dotnet add package Bit.Bink
Then the namespace, in _Imports.razor. Points and sizes in the API are
System.Numerics.Vector2, so code that builds documents usually wants that namespace too:
@using Bit.Bink @using System.Numerics
The stylesheet
The component's stylesheet, _content/Bit.Bink/bit-bink.css, is injected when the app starts by
the package's initializer (Bit.Bink.lib.module.js). It is layout only - the stacked canvases,
the input surface, the text editor - and leaves the look of the surrounding UI to you. To control it
yourself, link it in the host page and the automatic injection stands down:
<link rel="stylesheet" href="_content/Bit.Bink/bit-bink.css" />
A first canvas
<BinkCanvas Height="400px" /> is already a working canvas: pointer and stylus input,
pressure-aware ink, and undo and redo on the keyboard. Touch draws once EnableTouchGestures is
set. Bind DocumentChanged or HistoryChanged whenever your own markup reads canvas
state such as CurrentDocument.IsEmpty or History.CanUndo: a child component cannot
re-render its parent by itself, and drawing never re-renders anything.
<BinkCanvas @ref="_canvas" Height="260px" EnableTouchGestures="true" DocumentChanged="() => StateHasChanged()" /> <button @onclick="() => _canvas!.Undo()">Undo</button> <button @onclick="() => _canvas!.Clear()" disabled="@IsEmpty">Clear</button> @code { private BinkCanvas? _canvas; private bool IsEmpty => _canvas?.CurrentDocument.IsEmpty ?? true; }
Brushes and tools
Brush decides how ink looks and Tool what pointer input does. The built-in brushes
are BinkPenBrush, BinkPencilBrush, BinkMarkerBrush,
BinkHighlighterBrush, BinkCalligraphyBrush and BinkPixelEraserBrush; the
tools are BinkDrawTool, BinkEraserTool, BinkSelectTool,
BinkShapeTool, BinkPolylineTool, BinkTextTool and
BinkPanTool. Brushes are immutable records, so a variant is derived with with.
Shapes take their look from ShapeStyle, and nothing else has to be told that the tool changed.
<BinkCanvas Tool="_tool" Brush="_brush" Height="400px" /> @code { private IBinkTool _tool = new BinkDrawTool(); private BinkBrush _brush = new BinkPenBrush { Color = BinkColor.Parse("#1d4ed8"), Width = 5f }; private void UseRed() => _brush = _brush with { Color = BinkColor.Parse("#dc2626") }; private void UseEraser() => _tool = new BinkEraserTool { Mode = BinkEraserMode.Stroke, Radius = 12f }; private void UseArrow() => _tool = new BinkShapeTool(BinkShapeKind.Arrow); }
For a colour picker's "pick from screen" button, PickColorAsync opens the browser's eyedropper.
Only Chromium browsers on the desktop have one, so ask SupportsEyeDropperAsync before offering it,
and call it straight from the click, which is what lets the browser open it. The whiteboard has one.
if (await _canvas.PickColorAsync() is { } picked) _brush = _brush with { Color = picked };
Undo, redo and the keyboard
Undo stores the inverse of each change, never a snapshot, and every gesture is one step however many frames
it took. History says what the buttons would do - CanUndo, CanRedo,
UndoLabel and the stacks themselves, for a history list. HistoryLimit (200 steps)
and HistoryMemoryBudget bound what it keeps.
_canvas.Undo(); _canvas.Redo(); _canvas.Clear(); // one undo step, like everything else _canvas.DeleteSelection(); string? next = _canvas.History.UndoLabel; // "Add stroke", "Move", "Erase"...
The canvas takes focus as soon as it is drawn on, so its shortcuts work for someone who just used a mouse or a pen: Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y, Ctrl+A, Delete, Escape, Ctrl+D to duplicate, Ctrl+] and Ctrl+[ for the stacking order, and Ctrl with 0, 9, + or - for the view. Ctrl is Command on macOS. The complete map, with stepping through elements by keyboard alone, is on input and accessibility.
Save, load and export
The drawing is a vector document: save it anywhere - a database column, a file, a blob - and load it back to
keep editing. Use TryDeserialize for anything that came from outside your code; it reports a
reason instead of throwing. IsDirty says whether anything changed since MarkSaved,
for an "unsaved changes" prompt. Exports go through the same renderer as the screen, so they match it.
string json = BinkSerializer.Serialize(_canvas.CurrentDocument); if (BinkSerializer.TryDeserialize(json, out BinkDocument? loaded, out string? error)) _canvas.LoadDocument(loaded!); bool unsaved = _canvas.CurrentDocument.IsDirty; string svg = await _canvas.ExportSvgAsync(); byte[] png = await _canvas.ExportPngAsync(new BinkPngExportOptions { Scale = 3f }); byte[] jpeg = await _canvas.ExportImageAsync(BinkImageFormat.Jpeg, quality: 0.85); await _canvas.SaveSvgAsync("drawing.svg"); // offers the file as a download
A drawing without a canvas
Everything except BinkCanvas is plain .NET: the document, its elements, undo, saving and both
exporters run on a server, in a console application or in a unit test, with no browser at all. The picture
beside this code was built by it and written by BinkSvgExporter; no canvas was involved.
var document = new BinkDocument(new BinkDocumentSettings { Width = 400, Height = 160 }); var points = BinkStrokePoints.FromPositions([new(40, 112), new(120, 52), new(200, 104), new(280, 48), new(360, 100)]); document.AddElement(new BinkStroke(points, new BinkPenBrush { Width = 7f, Color = blue })); document.AddElement(new BinkRectangleShape(new BinkRect(16, 16, 368, 128)) { CornerRadius = 12f, Style = frame }); document.AddElement(new BinkTextElement(new Vector2(30, 26), "Built in C#") { Style = label }); string svg = BinkSvgExporter.Export(document); byte[] png = BinkPngExporter.Export(document); // the pure .NET rasterizer
Render modes
The same component works in every hosting model; what differs is where the engine runs, and so what
happens between a pen moving and ink appearing. This site runs on InteractiveWebAssembly.
| Hosting model | Where the engine runs, and what to know |
|---|---|
| WebAssembly | In the browser - the model the library is designed for. The command buffer reaches JavaScript as a view over managed memory, so a redraw is one call with no serialization; UsesFastRenderPath reports it. Outside AOT builds Bink can also be lazy loaded: nothing of it is registered. |
| Server | On the server: input travels over the circuit once per animation frame, and WetInk (on by default) draws a provisional trail while a batch is in flight. |
| Web App | Mark the page interactive - @rendermode InteractiveWebAssembly for drawing pages. Prerendering is handled: the canvas renders inert markup and attaches when interactivity arrives. A page that lazy loads Bink takes its render mode from Routes instead, or loads the assembly itself. |
| Hybrid | In-process in MAUI, WPF or Windows Forms, with the canvas in the embedded WebView over the standard IJSRuntime path. |
Lazy loading on WebAssembly
Bink registers nothing, so nothing has to be taken out of Program.cs, and a WebAssembly app can
fetch it only when someone opens a page that draws. Mark the assembly as lazy loaded in the project that runs in
the browser, outside AOT builds, with a runtime switch next to the mark so the router knows the assembly is there
to load, and load it before that page first renders:
<!-- AOT builds are left out: see below. --> <ItemGroup Condition=" '$(RunAOTCompilation)' != 'true' "> <BlazorWebAssemblyLazyLoad Include="Bit.Bink.wasm" /> <RuntimeHostConfigurationOption Include="MyApp.LazyLoadsBink" Value="true" Trim="true" /> </ItemGroup>
@* App.razor - in a Blazor Web App, the client project's Routes.razor: the router waits for OnNavigateAsync before it renders the page. typeof(Program) is the project the router's file is in, in either kind of app. *@ @using Microsoft.AspNetCore.Components.WebAssembly.Services @inject LazyAssemblyLoader LazyAssemblyLoader <Router AppAssembly="typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsync"> ... </Router> @code { // Set only where Bit.Bink.wasm is marked: loading an assembly that is not marked throws. private static readonly bool LazyLoadsBink = AppContext.TryGetSwitch("MyApp.LazyLoadsBink", out var on) && on; private async Task OnNavigateAsync(NavigationContext context) { // The pages that draw: fetch Bink before they render. A second call loads nothing again. if (LazyLoadsBink && IsDrawingPage(context.Path)) await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bink.wasm"]); } // /whiteboard and the routes beneath it, such as /Whiteboard/2 (routes match regardless of case), but not // /whiteboard-settings. Add every other route that renders Bink. The path keeps any query and fragment. private static bool IsDrawingPage(string path) { path = path.Split('?', '#')[0]; return path.Equals("whiteboard", StringComparison.OrdinalIgnoreCase) || path.StartsWith("whiteboard/", StringComparison.OrdinalIgnoreCase); } }
The stylesheet is still injected at startup, since the package's Blazor initializer does not wait for the assembly, and the canvas imports its browser module when it attaches; the zero-copy render path works from the lazily loaded assembly as well.
- Only what renders after the assembly has loaded may use Bink's types - the pages it is loaded for and a layout only they use, not
App.razor,Routes.razor, a layout every page shares orProgram.cs. Those pages can hold the canvas and fields of Bink's types, structs included. The method that callsLoadAssembliesAsynccannot: WebAssembly resolves what a method refers to when the method first runs, which is before the load, and does not retry. - No public type in an assembly the router reads in the browser - the app's own assembly first of all, the client project's in a Blazor Web App - may derive from or implement one of Bink's, close a generic type over one or constrain a type parameter to one: no public
BinkBrush,BinkElement,BinkElementConverter<T>, tool, render context, text rasterizer, collaboration transport or document store, noList<BinkStroke>subclass orIComparer<BinkElement>, no component that@inheritsone of Bink's and none with@typeparam TElement where TElement : BinkElement. The router reads those types when it first builds its route table, after the first navigation'sOnNavigateAsync, so such a type fails the app on its first page only when the app is opened away from a page that draws: try it from one that does not. Aninternalclass, or aprivateone nested in a page, is fine; a public one goes in a library referenced from the client project and lazy loaded together with Bit.Bink: mark it in the sameItemGroup(<BlazorWebAssemblyLazyLoad Include="MyApp.Drawing.wasm" />) and load both (LoadAssembliesAsync(["Bit.Bink.wasm", "MyApp.Drawing.wasm"])). - Register custom brushes and element types once, from code that runs after the load - the static constructor of a class in that library, run by a method the drawing page's
OnInitializedcalls, say. Registering replaces an earlier registration of the same kind and drops the brush registry's cached default for it, so registering on every page open rebuilds that brush each time. - In a Blazor Web App only the browser lazy loads, so give
Routesa render mode inApp.razorthat brings the router - and itsOnNavigateAsync- to the browser. UnderInteractiveWebAssemblyit runs there once the app has started. UnderInteractiveAutoit runs over a server circuit on the first visit and in the browser on later ones: a first visit draws on the server, and the browser downloads Bink on a later one. - With per-page render modes the router renders statically on the server and never loads the assembly in the browser, so a page that draws fails there with
Could not load file or assembly 'Bit.Bink'once it is interactive. Such a page loads Bink itself: it names none of Bink's types, awaitsLoadAssembliesAsyncinOnInitializedAsync, and only then renders a component of yours that holds the canvas. - Every host other than standalone WebAssembly registers
LazyAssemblyLoaderitself when something it renders injects it - the server project, whereRoutes.razorruns while it is prerendered and over the circuit underInteractiveAuto, and a Hybrid host that shares the router's file:builder.Services.AddScoped<LazyAssemblyLoader>(). Outside the browser it downloads nothing, but loads each assembly the call names from the ones the app references and throws if one is missing; a library lazy loaded with Bit.Bink reaches the server through the client project's reference to it. - The condition leaves AOT builds out. AOT compiles every assembly into
dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup. The switch is set only where the mark is, so an AOT build skipsLoadAssembliesAsyncas well: loading an assembly that is not marked throws.
When the canvas cannot start
If the browser layer cannot load - a content security policy blocks it, or static web assets are not served -
the canvas stays inert instead of throwing and taking the page down. Ready is not raised;
Unavailable is, with the reason, which stays available as AttachFailed, and the canvas
tells screen readers itself. The live canvas above handles it this way. While a page prerenders, the canvas is
inert markup too, but nothing has failed, so AttachFailed stays null and it attaches when
interactivity arrives.
<BinkCanvas Unavailable="reason => _unavailable = reason" /> @if (_unavailable is not null) { <p role="alert">Drawing is unavailable: @_unavailable</p> }
The component needs no eval and no inline script: its browser layer and its initializer are
modules from your own origin, and the stylesheet it injects is too, so script-src 'self' and
style-src 'self' are enough. Allow your CDN as well if static web assets are served from one.
How it fits together
One rendering path serves the screen, SVG export and PNG export, so an exported file always matches what was drawn. Pointer input never triggers a Blazor render: samples arrive once per frame, the active tool processes them, and only the affected canvas layer is redrawn.
Pointer events (browser) -> batched once per animation frame -> BinkStrokeBuilder spacing filter, streamline smoothing, pressure -> BinkStroke + BinkBrush immutable vector model -> BinkDrawingOperation the unit of undo, diffing and collaboration -> BinkDocument layers of elements -> IBinkRenderContext canvas commands, SVG, or the built-in rasterizer
Every change to a document is an operation, applied with Apply, which returns its inverse. That
inverse is all undo stores - never a snapshot - and the operation is what collaboration sends. Elements are
immutable records with a stable id: an edit is a copy made with with that replaces the original,
sharing its points. BeginBatch makes a burst of changes one event and one undo step.
BinkDrawingOperation inverse = document.Apply(new BinkAddElementOperation(layerId, stroke)); using (document.BeginBatch("Import")) { foreach (BinkStroke s in strokes) document.AddElement(s); }