在别人的前端demo中看到了鼠标画图这一项目,略感兴趣,于是读其代码,实现其功能。
点此体验
用鼠标画图的功能不是很难,原代码将html、css、javascript全部放在一份文档里都不算长。为了更好的阅读,我将其分成了三份。
html
在<head>标签中引用css和javascript代码
在<body>标签中构造按钮区域以及canvas画布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>鼠标画图</title> <script src="mouseDraw.js"></script> <link rel="stylesheet" href="mouseDraw.css"/> </head> <body> <div id="button"> <input type="button" value="重画"/> </div>
<canvas id="can" width="500px" height="500px"></canvas> </body> </html>
|
css
无解说
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @charset "utf-8"; body{ background: #CCC; text-align: center; } #button{ margin: 50px auto; width: 200px; } #can{ background: white; margin-top: -50px; display: inline-block; }
|
javascript
1.创建画布
2.获取按键元素,并赋予清除功能
3.画布中实现画图功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| window.onload=function(){ var can=document.getElementById("can"); var con=can.getContext("2d"); var inp=document.getElementsByTagName("input"); inp[0].onclick=function(){ can.width=can.width; } can.onmousedown=function(ev){ var ev=ev||event;
con.moveTo(ev.clientX-can.offsetLeft,ev.clientY-can.offsetTop); document.onmousemove=function(ev){ var ev=ev||event; con.lineTo(ev.clientX-can.offsetLeft,ev.clientY-can.offsetTop); con.stroke(); } document.onmouseup=function(){ document.onmousedown=document.onmousemove=null; } } }
|
尚需改进之处
1.该清除为擦除
2.改变画笔颜色大小等属性
3.改变画布大小
4.待定