用鼠标在canvas上画个性图形-LMLPHP

点击(此处)折叠或打开

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>canvas上鼠标画图</title>
  6. </head>
  7. <body>
  8.     <canvas id="myCanvas" width="600" height="600" style="border:1px solid #ccc"></canvas>
  9.     <div id="intend"></div>
  10.     <script>
  11.         /*思路如下:
  12.         1、鼠标按下时获得此时坐标,作为moveTo()绘图开始坐标,事件为onmousedown
  13.         2、鼠标滑动时,时刻获得鼠标的坐标,作为lineTo()绘图结束坐标,并绘制图形 事件为onmousemove
  14.         3、鼠标松开时,执行onmouseup事件,获得此时坐标,作为最终坐标,并移除onmousemove事件
  15.         */
  16.       var c=document.getElementById('myCanvas');
  17.       var ctx=c.getContext('2d');
  18.       var bX,bY,eX,eY;
  19.       var timer;
  20.       ctx.strokeStyle="red";

  21.       function mouseM(e){ //经过实践,如果把该函数直接写在监听事件内(c.removeEventListener('mousemove',mouseM,false) ),鼠标松开事件不会发生,因为写在监听事件内,就相当于立即执行了
  22.           e=e||window.event;
  23.           eX=e.clientX;
  24.           eY=e.clientY;
  25.           ctx.lineTo(eX,eY);
  26.         ctx.stroke();
  27.       }
  28.       c.addEventListener('mousedown',function(e){ //鼠标按下事件
  29.                e=e||window.event;
  30.          bX=e.clientX;
  31.          bY=e.clientY;
  32.          ctx.moveTo(bX,bY);
  33.          c.addEventListener('mousemove',mouseM,false); //增加onmousemove事件
  34.      },false)

  35.       c.addEventListener('mouseup',function(e){ //鼠标松开事件
  36.           e=e||window.event;
  37.           c.removeEventListener('mousemove',mouseM,false) //移除onmousemove事件
  38.           eX=e.clientX;
  39.           eY=e.clientY;
  40.           ctx.lineTo(eX,eY);
  41.           ctx.stroke();     
  42.       },false)

  43.     </script>
  44. </body>
  45. </html>

08-31 12:25