<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #cvs{ margin: 50px; border: 1px solid #999999; } </style> </head> <body> <canvas id="cvs" width="500" height="400"></canvas> <button>画画</button> <button>清除</button> <button>重画</button> </body> <script type="text/javascript"> // 通过JavaScript使用document.getElementById()方法来确定正确的画布 var cvs = document.getElementById("cvs") //每个画布都必须要有一个context(上下文)的定义 var ctx = cvs.getContext("2d") //获取btn var btn=document.getElementsByTagName('button') //添加点击事件 btn[0].onclick=function(){ cvs.onmousedown=function(e){ var Event=e||window.event //确定cvs的开始路径 ctx.beginPath() ctx.moveTo(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop) document.onmousemove=function(e){ var Event=e||window.event //路径移到画布中的指定点 , 即起点 ctx.lineTo(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop) ctx.strokeStyle='blue' ctx.lineWidth=5; ctx.stroke() } document.onmouseup=function(){ document.onmousedown=null document.onmousemove=null } } } //清除画布 btn[1].onclick=function(){ cvs.onmousedown=function(e){ var Event=e||window.event document.onmousemove=function(e){ var Event=e||window.event ctx.clearRect(Event.clientX-cvs.offsetLeft,Event.clientY-cvs.offsetTop,50,50) } document.onmouseup=function(){ document.onmousedown=null document.onmousemove=null } } } //清除canvas btn[2].onclick=function(){ ctx.clearRect(0,0,cvs.width,cvs.height) } </script> </html>