使用Javascript画布上的单击侦听器获取光标x和y值

时间:2016-05-24 13:14:54

标签: javascript canvas

当用户点击画布时,我需要光标的x和y值。我已经浏览了整个互联网并找到了许多不同的方法来做到这一点,但我相信它们不起作用,因为我清除并用框架更新画布。我能够获得关键点击工作。

我只是学习代码并需要大量解释。

以下是我的代码的简化版本:

var canvas_area = {
canvas : document.createElement("canvas"),
start : function() {
    this.canvas.width = canvas_width;
    this.canvas.height = canvas_height;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
    window.addEventListener('keydown', function (e) {
        e.preventDefault();
        canvas_area.keys = (canvas_area.keys || []);
        canvas_area.keys[e.keyCode] = (e.type == "keydown");
    })
    window.addEventListener('keyup', function (e) {
        canvas_area.keys[e.keyCode] = (e.type == "keydown");            
    })
    canvas.addEventListener('onmousedown', function(event) {
        canvas_area.cursor_position = event.clientX + ", " + event.clientY;
    })
},
stop_bar : function() {
    clearInterval(this.interval);
},    
clear : function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}

function updateGameArea() {
     canvas_area.clear();

     if (canvas_area.keys && canvas_area.keys[27]) {alert("pause");}//press escape key to use (27 is the escape key)
     if (canvas_area.cursor_position){
         alert(canvas_area.cursor_position);
     }//does not work

2 个答案:

答案 0 :(得分:1)

如果你从“onmousedown”改为“mousedown”,它应该有用。

在jsbin上查看我的小提琴

http://jsbin.com/pimeri/81/edit?html,css,js,output

var elem = document.getElementById('canvas');

elem.addEventListener('mousemove', function(event) {
  var x =  parseInt(event.pageX - elem.offsetLeft );
  var y =  parseInt(event.pageY - elem.offsetTop );
})

elem.addEventListener('mousedown', function(event){
  var x =  parseInt(event.pageX - elem.offsetLeft );
  var y =  parseInt(event.pageY - elem.offsetTop );
})

elem.addEventListener('mouseup', function(event){
  var x =  parseInt(event.pageX - elem.offsetLeft );
  var y =  parseInt(event.pageY - elem.offsetTop );
})

答案 1 :(得分:0)

canvas_area.canvas.addEventListener("click", getClickPosition, false);
function getClickPosition(e){
var xPosition = e.clientX;
    var yPosition = e.clientY;
return {x: xPosition, y: yPosition}
}