1. 程式人生 > 其它 >canvas 實現簽字功能 -- 支援匯出生成的img 格式base64

canvas 實現簽字功能 -- 支援匯出生成的img 格式base64

1、html <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style>   canvas {     border: 1px solid #e6e6e6;   } </style>
<body>   <div class="box">     <canvas class="canvas" width="500" height="500"></canvas>     <br>     <button class="btn">繪製</button>     <br>     <img class="img" src="">   </div>   <script src="./1-copy.js"></script> </body> </html> 2、js
(() => {   var x, y   var canvas = $('.canvas')   var ctx = canvas.getContext('2d') //初始化畫筆
  canvas.onmousedown = function (event) {     x = event.clientX - this.offsetLeft //this 指的是canvas     y = event.clientY - this.offsetTop     document.onmousemove = function (event) {       var x1 = event.clientX - canvas.offsetLeft       var y1 = event.clientY - canvas.offsetTop       sign(x, y, x1, y1, ctx)       x = x1       y = y1     }   }   canvas.onmouseup = function () {     document.onmousemove = null   }
  $('.btn').onclick = function () {     let imgData = canvas.toDataURL() //將畫布的內容轉為base64     $('.img').src = imgData   } })()
function $(domName) {   return document.querySelector(domName) }
function sign(x, y, x1, y1, ctx) {   ctx.beginPath() //重新開始繪畫   ctx.globalAlpha = 1 //畫布是否透明   ctx.lineWidth = 1 //線的粗細   ctx.moveTo(x, y)//起始點   ctx.lineTo(x1, y1) //結束點   ctx.closePath()//結束繪畫   ctx.stroke() //新增邊框 }