JavaScript/jQuery 签名板

JavaScript/jQuery signature pad

想问一下是否有办法将 <canvas> 的内容传输到另一个 <div>。这样签名后就可以在转入的<div>里面预览了。

我在之前的项目中使用过这个库https://github.com/szimek/signature_pad,签名看起来很真实,就像用钢笔写的一样。

这个库可以将签名保存到文件中,所以我在之前的项目中所做的是,一旦我提交了表单,签名就会被保存,并且可以通过将源文件附加到 <img>元素.

我想做的是我有一个 <button> 将显示一个包含签名板的模态,一旦模态关闭,签名将转移到另一个 <div> 其中它的大小将根据 div 的大小缩小,而无需将签名保存在文件中。

谢谢。

看看 HTMLCanvasElement.toDataURL. This will give you an image of the canvas as a Data URI,然后您可以将其作为图片添加到您的页面。

这是一个简单的例子:

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>