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 …
2
Answers
I managed to workaround my apparent inability to retrieve and subsequently use, the signature pad object, by storing it at creation in a data node on the canvas element.
I can then get it later
I've accepted James' answer, as using a global variable is probably more conventional and a logical extension of the normal single instance method. I just didn't clue on to that idea for storing multiple objects. That's nice. Note taken about
var canvas = this;
You can create a global variable which stores all the signaturePads when they are being created.
Later on, when you have the id of the canvas and want the signaturePad