javascripthtmlcsselectronic-signaturesignaturepad

Is there a way to change stroke color in html canvas using css


I have in my page a signature pad where the user can make an electronic signature. I am using js librairy SignaturePad(https://github.com/szimek/signature_pad).

My signature pad background color is black so I have set my stroke color to white. After saving the signature in my DB you have the option to print a report with the signature in it but this time the background is white.

My problem is that since the user is signing in white when you try to print the report, you can't see the signature since it's white on white.

Does anybody have an idea on how i could like change the signature color to white using css or other method to keep the default color(black) when im saving the signature in my DB ?


Solution

  • The penColor is saved on the points/url when you save the signature.

    You can use getData() to get all the points, then use forEach() to loop over them and change the penColor accordingly.

    const data = signaturePad.toData();
    data.forEach(p => p.penColor = 'black')
    

    The backgroundColor can be changed on run-time as desired

    signaturePad.backgroundColor = 'white'
    

    Demo:

    1. Create with backgroundColor: 'black' and penColor: 'white'
    2. Press the button
    3. backgroundColor is set to white
    4. Change the penColor as described above
    5. Re-draw using fromData

    var canvas = document.getElementById('signature-pad');
    
    var signaturePad = new SignaturePad(canvas, { backgroundColor: 'black', penColor: 'white' });
    
    document.getElementById('save-png').addEventListener('click', function () {
        if (signaturePad.isEmpty()) {
          return alert("Please provide a signature first.");
        }
    
        const data = signaturePad.toData();
        data.forEach(p => p.penColor = 'black')
        signaturePad.backgroundColor = 'white'
    
        signaturePad.fromData(data, { clear: true });
    });
    <script src="https://szimek.github.io/signature_pad/js/signature_pad.umd.js"></script>
    
    <div class="wrapper">
      <canvas id="signature-pad" class="signature-pad" width=400 height=200></canvas>
    </div>
    
    <button id="save-png">Press to re-draw</button>