2014-03-24 69 views
1

想知道是否可以使用鼠標事件(例如mousedown)在畫布上添加/移除圓圈。要點可以移動畫布上繪製的棋子。在這裏,我的代碼繪製了碎片,我添加了事件偵聽器,但我不知道如何繪製另一個碎片,而是單擊畫布上的某處。HTML canvas Javascript mouse event,without jQuery

<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> 

感謝您的幫助

+0

A [小提琴](http://jsfiddle.net/)將有所幫助。 –

+0

它不能正常工作,因爲我主要不知道如何使用它 – TCM

回答

0

您可以偵聽鼠標按下和mouseup畫布這樣的事件:

// get references to the canvas and its context 

var canvas=document.getElementById("canvas"); 
var ctx=canvas.getContext("2d"); 

// get the bounding box of the canvas 
// (needed when calculating the mouse position) 

var BB=canvas.getBoundingClientRect(); 
var offsetX=BB.left; 
var offsetY=BB.top; 

// tell the browser to trigger handleMousedown & handleMouseup 
// in response to mouse events 

canvas.onmousedown=handleMousedown; 
canvas.onmouseup=handleMouseup; 

你可以以這樣的鼠標事件作出迴應:

function handleMousedown(e){ 

    // tell the browser we're handling this event 

    e.preventDefault(); 
    e.stopPropagation(); 

    // calculate the mouse position 

    var mouseX=e.clientX-offsetX; 
    var mouseY=e.clientY-offsetY; 

    //now do your mouse down stuff 
} 

function handleMouseup(e){ 

    // tell the browser we're handling this event 

    e.preventDefault(); 
    e.stopPropagation(); 

    // calculate the mouse position 

    var mouseX=e.clientX-offsetX; 
    var mouseY=e.clientY-offsetY; 

    //now do your mouse up stuff 
} 

這裏有一個演示:http://jsfiddle.net/m1erickson/tP3m4/