@page "/signature" Signature ยท Bink

Signature

A production signature field: capture, clear, undo, validate and export. The signature is stored as vector ink, so it can be re-rendered at any size, embedded in a PDF as SVG, or rasterized at print resolution.

@* A fixed aspect signing area with a baseline, the way a paper form has one. The line and its caption are printed on the paper, so they take the paper's colours (demo.css) rather than the theme's. *@
Ink length @_ink.Length.ToString("0") units @_ink.StrokeCount strokes in @_ink.Duration.TotalSeconds.ToString("0.0") s
@_message
@if (_saved is not null) {

Stored signature

This is the document as it would be persisted. It is compact vector data, not an image: @_savedBytes bytes for @_saved.ElementCount strokes. It carries signed-at and purpose metadata, set with SetMetadata, which the format keeps for the application; the JSON is shown in the readable form, and the bytes counted are the compact one.

Re-rendered from the stored document
@* The export has a transparent background and dark ink, so it is shown on paper in either theme. *@
@((MarkupString)_savedSvg)
Serialized document
@_savedJson
}

Validation and the accepted state

A scribble of one dot is not a signature. The page measures the ink - its length, the number of strokes and how long the pen was down - and enables Accept signature only past a minimum length: a real validation rule that the vector model makes easy to express. Accepting makes the field ReadOnly, the way ink on paper is final, until the signer chooses to sign again.

BinkInkMetrics ink = BinkDocumentQuery.MeasureInk(_canvas.CurrentDocument);
bool valid = ink.Length > 120f;   // also ink.StrokeCount, ink.Duration, ink.Bounds

The message beside the buttons comes from StrokeCompleted, which hands over each finished stroke: its Input.HasRealPressure says whether a pen measured the pressure or the width was derived from drawing speed. While the field is read only, drawing, undo, redo and the editing shortcuts are refused (zooming still works), and its accessible name changes from "Sign here" to "Accepted signature".

A field inside a form

Whether a finger on a touch screen signs or scrolls the page is the one decision a signature field has to make, because no setting gets both. This field sets EnableTouchGestures, so a finger signs on a phone. In a long form that has to keep scrolling past the field, leave it off, as it is by default: the canvas then sets touch-action: pan-x pan-y, a finger scrolls, and a stylus still signs because a pen is not a touch pointer. The wheel is left to the page either way (WheelMode is None by default), so a mouse wheel over the field still scrolls the form.

@@* EnableTouchGestures="false": a finger scrolls the form, and a pen still signs. *@@
<BinkCanvas Height="200px" AriaLabel="Sign here"
            EnableTouchGestures="true"
            ReadOnly="_accepted"
            StrokeCompleted="OnStrokeCompleted"
            DocumentChanged="() => StateHasChanged()" />

The clipboard and dropping files stay off, as they are by default, so nobody can paste or drop a picture of a signature into the field. The signing line and its caption are printed over the canvas by the page, not drawn into the document, so they never appear in what is saved or exported.

Export cropped to the ink

BinkExportRegion.Content crops an export to what was drawn, and a transparent background lets the signature sit on whatever document it is placed into. The stored copy above is exported the same way, with BinkSvgExporter on the document rather than through the canvas.

await _canvas.SavePngAsync("signature.png", new BinkPngExportOptions
{
    Region = BinkExportRegion.Content,
    Padding = 12f,
    Scale = 3f,
    Background = BinkColor.Transparent,
});
@code { private BinkCanvas? _canvas; private CanvasStatus? _status; private BinkBrush _brush = new BinkPenBrush { Width = 3.5f, Color = BinkColor.Parse("#0f172a"), TaperEnd = 8f }; private string _color = "#0f172a"; private float _width = 3.5f; private BinkInkMetrics _ink; private bool _locked; private static readonly string[] InkColors = ["#0f172a", "#1d4ed8"]; private string _message = "Sign to continue."; private BinkDocument? _saved; private string _savedSvg = string.Empty; private string _savedJson = string.Empty; private int _savedBytes; private bool IsEmpty => _canvas?.CurrentDocument.IsEmpty ?? true; private bool CanUndo => _canvas?.History.CanUndo ?? false; private bool CanRedo => _canvas?.History.CanRedo ?? false; // A scribble of one dot is not a signature. Requiring a little ink is a real validation rule that the // vector model makes easy to express. private bool IsValid => _ink.Length > MinimumInkLength; private const float MinimumInkLength = 120f; private void SetColor(string color) { _color = color; _brush = _brush with { Color = BinkColor.Parse(color) }; } private void OnWidthChanged(ChangeEventArgs e) { if (float.TryParse(e.Value?.ToString(), System.Globalization.CultureInfo.InvariantCulture, out float value)) { _width = value; _brush = _brush with { Width = value }; } } private void OnStrokeCompleted(BinkStrokeEventArgs args) { // Stroke and document notifications can arrive in either order, so measure here as well. MeasureInk(); string captured = args.Stroke is { } stroke && stroke.Input.HasRealPressure ? "Captured with pen pressure." : "Captured."; _message = IsValid ? captured : captured + " Keep signing: the signature is still too short to accept."; } private void OnDocumentChanged(BinkDocumentChangedEventArgs args) { MeasureInk(); StateHasChanged(); } private void MeasureInk() => _ink = _canvas is null ? default : BinkDocumentQuery.MeasureInk(_canvas.CurrentDocument); private void Clear() { // Signing again unlocks the field. The stored copy below is kept until a new one is accepted. _locked = false; // The canvas still has ReadOnly set until this component re-renders, and a read only canvas ignores // Clear. Clearing the document directly is the same undoable edit, without waiting for that render. _canvas?.CurrentDocument.Clear(); _message = "Sign to continue."; } private void Accept() { if (_canvas is null || !IsValid) return; // Persisting a signature: crop to the ink, keep it as vector data, and label it for accessibility. BinkDocument document = _canvas.CurrentDocument.Clone(); document.SetMetadata("signed-at", DateTimeOffset.UtcNow.ToString("O")); document.SetMetadata("purpose", "signature"); _saved = document; _savedJson = BinkSerializer.Serialize(document, BinkSerializerOptions.Readable); _savedBytes = BinkSerializer.SerializeToUtf8Bytes(document).Length; _savedSvg = BinkSvgExporter.Export(document, new BinkSvgExportOptions { Region = BinkExportRegion.Content, Padding = 12f, Background = BinkColor.Transparent, Title = "Signature", IncludeElementDescriptions = true, }); // An accepted signature is final, the way ink on paper is: the field becomes read only until the // signer chooses to sign again. _locked = true; _message = "Signature accepted."; } private Task DownloadSvgAsync() => _canvas?.SaveSvgAsync("signature.svg", new BinkSvgExportOptions { Region = BinkExportRegion.Content, Padding = 12f, Background = BinkColor.Transparent, }) ?? Task.CompletedTask; private Task DownloadPngAsync() => _canvas?.SavePngAsync("signature.png", new BinkPngExportOptions { Region = BinkExportRegion.Content, Padding = 12f, Scale = 3f, Background = BinkColor.Transparent, }) ?? Task.CompletedTask; }