Simple Signature Pad (Blazor, Canvas, JS, .NET 5)

I had a project using a Blazor Signature package that kept throwing intermittent errors with its signature pad.  It appeared to be an issue between its interaction with Javascript, but since it was encapsulated within the package, I could’t debug it.

Instead of using a package, I decided to break it up by using the most popular JS signature pad ( and JSInterop in Blazor to facilitate the communication between .NET and Javascript.

For the quick demo:


Blazor Fiddle:



The important portion of this is the @ref as seen below.   This is the reference I used to understand this:   Without this, the canvas would be created and even signatures allowed but the connection between the element and .NET is lost, returning blank canvases/signatures every time.

<div class="alert alert-danger @signatureAlert">Signature Required.</div>
<label>Please Sign Below:</label><br />
<canvas id="signature-pad" class="signature-pad border" @ref="_canvas"></canvas>
<a id="clear-signature" class="btn btn-light border">Clear</a>

Add the reference in code:

public ElementReference _canvas;

Setup the signature canvas:

protected override async Task OnAfterRenderAsync(bool firstRender)
    if (firstRender)
        noSignature = await JsRuntime.InvokeAsync<string>("setSignature", _canvas);

SignaturePad.isEmpty() would not return an accurate value, so I handled this by capturing what a blank canvas looks like after it’s created into “noSignature” and then comparing it to submitted signature to test for blanks.



In the docs for Signature Pad, they often use the name of the “Id” (getElementById) to get the signature-canvas element.  In this example, you need to directly use the _canvas element passed from .NET.

function getImageData(element) {
    var saveImage = element.toDataURL();
    return saveImage;

The rest of the code you’ll need is all in the Github and Blazor Fiddle up above.

Any errors I returned in this solution were then a lot easier to debug as they were strictly in the Javascript side or the .NET side, not encapsulated in a package.




You may also like