javascriptjquerysignaturepad

JavaScript/jQuery signature pad


Would like to ask if there's a way for transferring <canvas> contents to another <div>. So that after putting the signature, it will be previewed on the inside of the <div> it was transferred to.

I've used this library https://github.com/szimek/signature_pad on our previous project and the signature looks real, like it was written by a pen.

This library can save the signature to a file, so what I did on our previous project is once I submit the form, the signature will be saved and it will be previewed by attaching the source file to an <img> element.

What I would like to do is I have a <button> that will show a modal that contains a signature pad and once the modal is closed, the signature will be transferred to another <div> wherein its size will shrink depending on the div's size without having to save the signature on a file.

Thanks.


Solution

  • Take a look at HTMLCanvasElement.toDataURL. This will give you an image of the canvas as a Data URI, which you can then add to your page as an image.

    Here's a simple example:

    let canvas = document.querySelector('canvas'),
        ctx = canvas.getContext('2d');
    
    // Draw something
    ctx.fillStyle = "lightgray";
    ctx.fillRect(0, 0, 200, 100);
    ctx.fillStyle = 'orange';
    ctx.fillRect(20, 20, 160, 60);
    ctx.fillStyle = 'black';
    ctx.font = "50px monospace";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("image", 100, 50);
    
    // Make the image and put it in the output
    let uri = canvas.toDataURL('image/png'),
        outdiv = document.querySelector('#out'),
        outimg = new Image();
    outimg.src = uri;
    outdiv.appendChild(outimg);
    <div style="display: inline-block;">
      <h6>Canvas with border</h6>
      <canvas width="200" height="100"
              style="border: 1px solid black;">
      </canvas>
    </div>
    
    <div style="display: inline-block;">
      <h6>Output image in a <code>div</code></h6>
      <div id="out"></div>
    </div>