2013-06-27 15 views
3

我有以下函數來獲得鼠標點擊位置(座標)。canvas在鼠標事件上獲得分數

$('#myCanvas').on('click', function(e) { 
    event = e; 
    event = event || window.event; 

    var canvas = document.getElementById('myCanvas'), 
      x = event.pageX - canvas.offsetLeft, 
      y = event.pageY - canvas.offsetTop; 
    alert(x + ' ' + y); 
}); 

我需要在點擊某個位置時獲得鼠標點,並且在拖動鼠標點位置之後還需要獲取鼠標點位置。

即, mousedown點和mouseup點。

回答

8

嘗試有點不同的設置:

var canvas = myCanvas; //store canvas outside event loop 
var isDown = false;  //flag we use to keep track 
var x1, y1, x2, y2;  //to store the coords 

// when mouse button is clicked and held  
$('#myCanvas').on('mousedown', function(e){ 
    if (isDown === false) { 

     isDown = true; 

     var pos = getMousePos(canvas, e); 
     x1 = pos.x; 
     y1 = pos.y; 
    } 
}); 

// when mouse button is released (note: window, not canvas here) 
$(window).on('mouseup', function(e){ 

    if (isDown === true) { 

     var pos = getMousePos(canvas, e); 
     x2 = pos.x; 
     y3 = pos.y; 

     isDown = false; 

     //we got two sets of coords, process them 
     alert(x1 + ',' + y1 + ',' +x2 + ',' +y2); 
    } 
}); 

// get mouse pos relative to canvas (yours is fine, this is just different) 
function getMousePos(canvas, evt) { 
    var rect = canvas.getBoundingClientRect(); 
    return { 
     x: evt.clientX - rect.left, 
     y: evt.clientY - rect.top 
    }; 
} 

那麼,爲什麼我們聽鼠標的窗口上?如果您將鼠標懸停在畫布外,然後釋放鼠標按鈕,則該事件不會在畫布上註冊。所以我們需要聽一個像窗口這樣的全球性事件。

由於我們已經在鼠標向下的事件中標記了我們的isDown,我們知道後面的鼠標「屬於」畫布(當我們檢查isDown標誌時)。

0

使用接收器像$( '#myCanvas')的mousedown和$( '#myCanvas')。鼠標鬆開

0

所以,你需要拖放?嗯,這很容易:首先你檢測到'onclick',如果你的目標(rect,circle,任何)保存點指向變量,'onmousemove'你移動對象,然後'onmousedown'你得到的最後一點。

希望它能幫助你!