How do I get the coordinates of a mouse click on a canvas element?
If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})
Get the mouse coordinates when clicking on canvas
You could achieve that by using the offsetX
and offsetY
property of MouseEvent
//setup canvasvar canvasSetup = document.getElementById("puppyCanvas");var ctx = canvasSetup.getContext("2d");guessX = 0; //stores user's click on canvasguessY = 0; //stores user's click on canvasfunction storeGuess(event) { var x = event.offsetX; var y = event.offsetY; guessX = x; guessY = y; console.log("x coords: " + guessX + ", y coords: " + guessY);}
<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick="storeGuess(event)"></canvas>
Determine X coordinate of a mouse click
Your problem is that you're handling the event in a parent of the status bar element, so .offsetX
is relative to the x position of parent and not the status bar.
Put the event handler on the status bar element itself and the .offsetX
property of the event will work as you expect.
Get X/Y Coordinates with Mouseclick
Here's exactly what you asked for.
Fiddle: http://jsfiddle.net/ZZEk8/118/
Add to HTML:
<span class="log"></span>
JS:
var clicks = [],
updatedClicks = "";
$('.clickable').on('click', function (ev) { //We don't use .bind() after jQuery 1.7, use .on() now.
var $div = $(ev.target);
var $display = $div.find('.display');
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
$display.text('x: ' + x + ', y: ' + y);
clicks.push(x + "/" + y);
updatedClicks += "coordinates" + " " + clicks.length + ":" + " " + clicks[clicks.length -1] + "<br />";
$('.log').html(updatedClicks);
});
UPDATE:
OP requested a way to limit the coords and delete one.
Fiddle: http://jsfiddle.net/ZZEk8/125/
var clicks = [],
updatedClicks = [],
limit = 5;
$('.clickable').on('click', function (ev) {
var $div = $(ev.target);
var $display = $div.find('.display');
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
$display.text('x: ' + x + ', y: ' + y);
//Stops adding at limit
if (clicks.length < limit){
addCoord(x,y);
}
});
$('.delete').on('change', function(ev) {
if(clicks.length){
var selection = this.value -1;
deleteCoord(selection);
} else { //If there are no coords to delete run this
return false;
}
});
function addCoord (x,y){
clicks.push(x + "/" + y);
updatedClicks.push("Coordinates" + ":" + " " + clicks[clicks.length -1] + "<br />");
$('.log').html(updatedClicks.join(" "));
}
function deleteCoord(selection) {
clicks.splice(selection, 1);
updatedClicks.splice(selection, 1);
$('.log').html(updatedClicks.join(" "));
}
Find mouse position relative to element
For people using JQuery:
Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.
You take the mouse position, and then subtract it from the parent element's offset position.
var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;
If you're trying to get the mouse position on a page inside a scrolling pane:
var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();
Or the position relative to the page:
var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();
Note the following performance optimisation:
var offset = $('#element').offset();
// Then refer to
var x = evt.pageX - offset.left;
In this way, JQuery does not have to look up #element
for each line.
Update
There is a newer, JavaScript-only version in an answer by @anytimecoder -- see also browser support for getBoundingClientRect().
Related Topics
Get Caret Index in Contenteditable Div Including Tags
Sort an HTML List with JavaScript
Populate One Dropdown List Based on the Selection of Other Dropdown List
How to Get HTML Elements from an Object Tag
How to Exchange Variables Between Two HTML Pages
Search and Highlight in Jquery
Links in <Select> Dropdown Options
Uploading Multiple Files to Google Drive with Google App Script
Jquery Select Option Click Handler
Download Canvas as Png in Fabric.Js Giving Network Error
Enter Key Press Behaves Like a Tab in JavaScript
Formdata.Append("Key", "Value") Is Not Working
How to Use JSON File in HTML Code
HTML Anchor Link - Href and Onclick Both
Access Event to Call Preventdefault from Custom Function Originating from Onclick Attribute of Tag
Reactjs: "Uncaught Syntaxerror: Unexpected Token <"
Play .Wav Sound File Encoded in Base64 with JavaScript
How to Use Greasemonkey to Selectively Remove Content from a Website