12:00:14
这是网上的一个手绘板,中间还是有很多不足,但是也有很多可以学习的地方。我发上来仅供参考,代码见下:
<!DOCTYPE html> <html> <head> <title>画板实验</title> <meta charset="UTF-8"> <meta name="viewport"content="width=device-width, initial-scale=1.0"> <style type="text/css"> body{background-color: white;} </style> </head> <body > <canvas id="myCanvas"></canvas> <div> <button onclick="clean();">清 空</button> <button onclick="save();">生成图片</button> </div> <img id=‘img‘ alt=‘请涂鸦……‘/> <script type="text/javascript"> var canvas, board, img; canvas = document.getElementById(‘myCanvas‘); img = document.getElementById(‘img‘); canvas.height = 300; canvas.width = 300; board = canvas.getContext(‘2d‘); var mousePress = false; var last = null; //开始 function beginDraw() { mousePress = true; } function drawing(event) { event.preventDefault(); if (!mousePress) return; var xy = pos(event); if (last != null) { board.beginPath(); board.moveTo(last.x, last.y); board.lineTo(xy.x, xy.y); board.stroke(); } last = xy; } function endDraw(event) { mousePress = false; event.preventDefault(); last = null; } function pos(event) { var x, y; if (isTouch(event)) { x = event.touches[0].pageX; y = event.touches[0].pageY; } else { x = event.offsetX + event.target.offsetLeft; y = event.offsetY + event.target.offsetTop; } // log(‘x=‘+x+‘ y=‘+y); return { x : x, y : y }; } function log(msg) { var log = document.getElementById(‘log‘); var val = log.value; log.value = msg + ‘n‘ + val; } function isTouch(event) { var type = event.type; if (type.indexOf(‘touch‘) >= 0) { return true; } else { return false; } } function save() { //base64 var dataUrl = canvas.toDataURL(); // dataUrl = dataUrl.replace("image/png","image/octet-stream"); img.src = dataUrl; } function clean() { board.clearRect(0, 0, canvas.width, canvas.height); } board.lineWidth = 1; board.strokeStyle = "#0000ff"; canvas.onmousedown = beginDraw; canvas.onmousemove = drawing; canvas.onmouseup = endDraw; canvas.addEventListener(‘touchstart‘, beginDraw, false); canvas.addEventListener(‘touchmove‘, drawing, false); canvas.addEventListener(‘touchend‘, endDraw, false); </script> </body> </html>
ps:报一下这个的缺点吧
1.功能太少,只有保存和清空,没有其他的撤销,反撤销
2.没有图片截取最小大小,没有自动大小(这个好解决)
(上面两个是根据我自己的需求得出的、、下面是真·问题)
3.鼠标点击完屏幕,移出区域之后会可以直接不点就能画,需要再在区域里点一下才可以取消效果,原因是仅仅定义了鼠标点击提起mouseup,并没有相应匹配的移出的事件。
时间: 2024-12-29 07:24:43