123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
- <title></title>
- <style>
- html,
- body {
- margin: 0;
- }
- .container {
- width: calc(100vw - 40px);
- height: calc(100vh - 40px);
- padding: 20px;
- }
- .canvas-body {
- width: calc(80vw);
- height: calc(80vh);
- margin: 20px auto;
- }
- #sign {
- background-color: #f3f5f7;
- border-radius: 4px;
- border: 1px dashed #0F6BFF;
- }
- .btns {
- width: calc(80vw - 40px);
- text-align: right;
- margin: 0 auto;
- }
-
- </style>
-
- </head>
- <body>
- <div class="container">
- <div id="canvas-body" class="canvas-body">
- <canvas id="sign" style="width: 100%; height: 100%;"></canvas>
-
- </div>
- <div class="btns">
- <button id="reset">重置</button>
- <button id="showImg">生成图片</button>
- </div>
- </div>
-
- <script>
- let canvasBody = document.getElementById('canvas-body');///canvas的外层区域
- let canvas = document.getElementById('sign');///canvas签字区域
- let reset = document.getElementById('reset');///重置按钮
- let showImg = document.getElementById('showImg');///生成图片按钮
-
- canvas.width = canvasBody.clientWidth;
- canvas.height = canvasBody.clientHeight;
- let ctx = canvas.getContext('2d');
- ctx.lineWidth = 10;
- ctx.strokeStyle = '#333';
- ctx.lineCap = 'round';
- ctx.lineJoin = 'round';
- let isDrawing = false;
- let dataURL = '';
- let initX;
- let initY;
- // 事件监听--开始绘制
-
- canvas.addEventListener("mousedown",function(e){
- isDrawing = true;
- initX = e.offsetX;
- initY = e.offsetY
- });
- canvas.addEventListener('mousemove', draw);
-
-
- canvas.addEventListener("mouseup",function(){
- isDrawing = false
- });
-
- canvas.addEventListener("mouseout",function(){
- isDrawing = false
- });
- // 绘制中...
- function draw(e) {
- if (!isDrawing) return
- ctx.beginPath();
- // 起点
- ctx.moveTo(initX, initY);
- // 终点
- ctx.lineTo(e.offsetX, e.offsetY);
- ctx.stroke();
- initX = e.offsetX;
- initY = e.offsetY
- }
- ///重置
- function clear() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- if (dataURL) {
- dataURL = '';
-
- }
- }
- function canvasToBase64() {
- dataURL = canvas.toDataURL();
- console.log(dataURL);
- alert(dataURL)
- }
- reset.addEventListener('click', clear);
- showImg.addEventListener('click', canvasToBase64);
- </script>
- <script>
-
- </script>
- </body>
- </html>
|