toDataURL

方法返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。

canvas.toDataURL(type, encoderOptions);

type 可选

图片格式,默认为 image/png

encoderOptions 可选

在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <!-- <script src="./index.js"></script> -->
  8. <title>签名</title>
  9. <style>
  10. .signature {
  11. position: relative;
  12. }
  13. .canvas {
  14. width: 100%;
  15. height: 700px;
  16. }
  17. .bottom {
  18. width: 100%;
  19. text-align: center;
  20. height: 3rem;
  21. line-height: 3rem;
  22. border-top: 1px solid #ccc;
  23. font-size: 1rem;
  24. }
  25. </style>
  26. </head>
  27. <body>
  28. <div class="signature">
  29. <div id="canvas" class="canvas">
  30. </div>
  31. <div class="bottom" onclick="submit()" style="cursor: pointer">保存签名</div>
  32. </div>
  33. <script>
  34. let draw = false
  35. window.onload = () => {
  36. canvas()
  37. }
  38. function canvas() {
  39. let c = document.getElementById("canvas")
  40. let canvas = document.createElement("canvas")
  41. let availHeight = document.documentElement.clientHeight
  42. let off = 0
  43. canvas.height = '700'
  44. canvas.width = c.clientWidth
  45. c.appendChild(canvas)
  46. let dr = canvas.getContext('2d')
  47. dr.strokeStyle = 'blue'
  48. canvas.addEventListener('mousedown', (e) => {
  49. draw = true
  50. dr.beginPath()
  51. })
  52. canvas.addEventListener('mousemove', (e) => {
  53. // console.log(e)
  54. if (draw) {
  55. dr.lineTo(e.pageX, e.pageY - off)
  56. dr.stroke()
  57. }
  58. })
  59. canvas.addEventListener('mouseup', (e) => {
  60. // console.log(e)
  61. draw = false
  62. })
  63. }
  64. function downLoad(url) {
  65. console.log(url)
  66. var oA = document.createElement("a");
  67. oA.download = '';
  68. oA.href = url;
  69. document.body.appendChild(oA);
  70. oA.click();
  71. oA.remove();
  72. }
  73. function submit() {
  74. let img = document.querySelector('canvas').toDataURL("image/png")
  75. downLoad(img)
  76. }
  77. </script>
  78. </body>
  79. </html>
文档更新时间: 2019-05-10 14:29