点击(此处)折叠或打开
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>canvas上鼠标画图</title>
- </head>
- <body>
- <canvas id="myCanvas" width="600" height="600" style="border:1px solid #ccc"></canvas>
- <div id="intend"></div>
- <script>
- /*思路如下:
- 1、鼠标按下时获得此时坐标,作为moveTo()绘图开始坐标,事件为onmousedown
- 2、鼠标滑动时,时刻获得鼠标的坐标,作为lineTo()绘图结束坐标,并绘制图形 事件为onmousemove
- 3、鼠标松开时,执行onmouseup事件,获得此时坐标,作为最终坐标,并移除onmousemove事件
- */
- var c=document.getElementById('myCanvas');
- var ctx=c.getContext('2d');
- var bX,bY,eX,eY;
- var timer;
- ctx.strokeStyle="red";
- function mouseM(e){ //经过实践,如果把该函数直接写在监听事件内(c.removeEventListener('mousemove',mouseM,false) ),鼠标松开事件不会发生,因为写在监听事件内,就相当于立即执行了
- e=e||window.event;
- eX=e.clientX;
- eY=e.clientY;
- ctx.lineTo(eX,eY);
- ctx.stroke();
- }
- c.addEventListener('mousedown',function(e){ //鼠标按下事件
- e=e||window.event;
- bX=e.clientX;
- bY=e.clientY;
- ctx.moveTo(bX,bY);
- c.addEventListener('mousemove',mouseM,false); //增加onmousemove事件
- },false)
- c.addEventListener('mouseup',function(e){ //鼠标松开事件
- e=e||window.event;
- c.removeEventListener('mousemove',mouseM,false) //移除onmousemove事件
- eX=e.clientX;
- eY=e.clientY;
- ctx.lineTo(eX,eY);
- ctx.stroke();
- },false)
- </script>
- </body>
- </html>