<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>网页签名</title> <style> * { margin: 0; padding: 0; } .wrap { margin: 50px; width: 500px; } canvas { border: 1px solid #000; } .save-btn { width: 200px; height: 30px; line-height: 30px; font-size: 16px; color: #999; cursor: pointer; border: 1px solid; text-align: center; margin: 0 auto; } </style> </head> <body> <div class="wrap"> <canvas id="canvas"></canvas> <div class="save-btn">保存</div> </div> <script> const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext("2d"); const saveBtn = document.querySelector(".save-btn"); canvas.width = 500; canvas.height = 300; let isDrawing = false; // 开始绘图 canvas.addEventListener("mousedown", (e) => { isDrawing = true; ctx.beginPath(); }); // 绘制 canvas.addEventListener("mousemove", (e) => { if (isDrawing) { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; ctx.lineWidth = 2; ctx.lineCap = "round"; ctx.strokeStyle = "red"; ctx.lineTo(x, y); ctx.stroke(); } }); // 停止绘图 canvas.addEventListener("mouseup", () => { isDrawing = false; }); // 开始绘图 canvas.addEventListener("touchstart", (e) => { isDrawing = true; ctx.beginPath(); }); // 绘制 canvas.addEventListener("touchmove", (e) => { if (isDrawing) { const rect = canvas.getBoundingClientRect(); const x = e.touches[0].clientX - rect.left; const y = e.touches[0].clientY - rect.top; ctx.lineWidth = 2; ctx.lineCap = "round"; ctx.strokeStyle = "red"; ctx.lineTo(x, y); ctx.stroke(); } }); // 停止绘图 canvas.addEventListener("touchend", () => { isDrawing = false; }); saveBtn.addEventListener("click", () => { save(); }); function save() { // 将画布内容转换为图片 canvas.toBlob(function (blob) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "canvas_image.png"; // 指定下载文件的名称 a.click(); }, "image/png"); } </script> </body> </html>
 
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号