I have code that generates multiple signature pads on a page, giving them a unique ID along the way. I would like to be able to do individual signaturePad.toDataURL() and calls and signaturePad.isEmpty() checks as I process a button click, by looping through the canvas elements. I would also like to do single signaturePad.clear() functions as required.
I haven't been able to figure out how to refer to the signature-pad instance that is attached to a given canvas element.
For clearing the signature, I've tried
$("body").on("click", ".signature-clear", function() {
var canvas = document.getElementById($(this).closest('.canvas-wrap').find('canvas').attr('id'));
var signaturePad = canvas.signaturePad();
});
But despite the canvas element being correctly targeted, I get the canvas.signaturePad
is not a function error.
I'm sure it will be simple
PS: I know that I can just do another new SignaturePad(canvas)
to clear the pad, but that is clunky (in my opinion) and doesn't help me save the signatures or check whether they have been signed.
For reference they are set up as follows:
$(".signature-pad").each(function () {
var canvas = document.getElementById($(this).attr('id'));
var signaturePad = new SignaturePad(canvas);
});
UPDATE:
I decided to try just using the canvas element itself to attach the signature pad functions to and the results were very confusing.
var canvas = document.getElementById($jq(this).closest('.canvas-wrap').find('canvas').attr('id'));
var signature = canvas.toDataURL();
Bizarrely, toDataURL()
WORKED!!! However, isEmpty() and clear() did not. Looking in to the console at the element there is a HTMLCanvasElementPrototype prototype listed and it mentions a few functions (including toDataURL() and others but not the complete set mentioned in the Doco. isEmpty()
is pretty key to have working.
Weird ...
You can create a global variable which stores all the signaturePads when they are being created.
const signaturePads = {}; // global object to store {"id1": ref1, "id2": ref2, etc}
$(".signature-pad").each(function () {
// the next line is a very roundabout way of doing var canvas = this; (or possibly this[0])
var canvas = document.getElementById($(this).attr('id'));
var signaturePad = new SignaturePad(canvas);
// store canvasId: sigpad in global var
signaturePads[canvas.id] = signaturePad;
});
Later on, when you have the id of the canvas and want the signaturePad
const sigPad = signaturePads[myCanvasId];
// do stuff with sigPad
if (sigPad.isEmpty()) {
console.log("it's empty");
}