html5 - HTML canvas Javascript mouse event, without jQuery -


was wondering if possible add/remove circle on canvas mouse event, such mousedown. main point being able move checker piece drawn on canvas. here code draws pieces, added event listener, don't know how draw piece clicking somewhere on canvas.

<script type="text/javascript"> var canvas=document.getelementbyid("checkerboard"); var context2d=canvas.getcontext("2d"); canvas.addeventlistener("mousedown", movep, false); function play(){     context2d.fillstyle="red";     for(var x=0; x<8; x++){         for(var y=0; y<3; y++){             if(((x+y)%2)==1){                 context2d.beginpath();                 context2d.moveto(x*80+5, y*80+40);                 context2d.arc(x*80+40, y*80+40, 30, 0, 2*math.pi);                 context2d.linewidth=15;                 context2d.strokestyle="#9f000f";                 context2d.stroke();                 context2d.fill();             }         }     }     context2d.fillstyle="grey";     for(var x=0; x<8; x++){         for(var y=5; y<8; y++){             if(((x+y)%2)==1){                 context2d.beginpath();                 context2d.moveto(x*80+5, y*80+40);                 context2d.arc(x*80+40, y*80+40, 30, 0, 2*math.pi);                 context2d.linewidth=15;                 context2d.strokestyle="#b6b6b4";                 context2d.stroke();                 context2d.fill();             }         }     } } </script> 

thanks help

you can listen mousedown , mouseup events on canvas this:

// references canvas , context  var canvas=document.getelementbyid("canvas"); var ctx=canvas.getcontext("2d");  // bounding box of canvas // (needed when calculating mouse position)  var bb=canvas.getboundingclientrect(); var offsetx=bb.left; var offsety=bb.top;  // tell browser trigger handlemousedown & handlemouseup // in response mouse events  canvas.onmousedown=handlemousedown; canvas.onmouseup=handlemouseup; 

and can respond mouse events this:

function handlemousedown(e){      // tell browser we're handling event      e.preventdefault();     e.stoppropagation();      // calculate mouse position      var mousex=e.clientx-offsetx;     var mousey=e.clienty-offsety;      //now mouse down stuff }  function handlemouseup(e){      // tell browser we're handling event      e.preventdefault();     e.stoppropagation();      // calculate mouse position      var mousex=e.clientx-offsetx;     var mousey=e.clienty-offsety;      //now mouse stuff } 

here's demo: http://jsfiddle.net/m1erickson/tp3m4/


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -