问题
I have an HTML file with a <canvas>
element and I am trying to get the mouse coordinates in the click
event. I am using this code:
secondCanvas.addEventListener('click', function(e) {
console.log(e.pageX)
}, false);
When I click on the top left point I get in console 500~ number, not zero... what do I need to do to get the coordinates of the mouse on the canvas?
回答1:
You should calculate the canvas mouse position by substracting the canvas element offset from the event offset (e.pageX
and e.pageY
).
Here's a link that explains how to get an element position in the dom, and the code should look like :
secondCanvas.addEventListener('click', function(e) {
var pos = {
x : e.pageX - canvasOffsetX,
y : e.pageY - canvasOffsetY
};
console.log(pos.x)
}, false);
回答2:
It's because you're getting page coordinates. I'm guessing you want the current mouse position within either one of your two canvases? Hopefully this will solve your problem:
http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
Also this stackoverflow is similar to yours and might give you a better understanding: Tracking mouse position in canvas when no surrounding element exists
Solution by user: lwburk
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
$('#canvas').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coordinateDisplay = "x=" + x + ", y=" + y;
writeCoordinateDisplay(coordinateDisplay);
});
回答3:
I use this code and it works perfectly for me. Once added, canvas mouse events have two new properties: canvasX, and canvasY which are properly mapped. Right after you obtained the canvas element, don't forget to call canvas.extendMouseEvents() and you're in business.
HTMLCanvasElement.prototype.extendMouseEvents = function() {
this.mapMouseEvent = function(ev) {
var r = this.getBoundingClientRect();
ev.canvasX = ev.pageX - r.left;
ev.canvasY = ev.pageY - r.top;
};
this.addEventListener("mousemove", this.mapMouseEvent);
this.addEventListener("click", this.mapMouseEvent);
this.addEventListener("contextmenu", this.mapMouseEvent);
this.addEventListener("dblclick", this.mapMouseEvent);
this.addEventListener("mousedown", this.mapMouseEvent);
this.addEventListener("mouseenter", this.mapMouseEvent);
this.addEventListener("mouseleave", this.mapMouseEvent);
this.addEventListener("mouseover", this.mapMouseEvent);
this.addEventListener("mouseout", this.mapMouseEvent);
this.addEventListener("mouseup", this.mapMouseEvent);
}
来源:https://stackoverflow.com/questions/10403214/html5-canvas-mouse-coordinates