I want to get the "inner offset", or rather the inner coordinates of a clicked element via the Javascript Click-Event. As you can see in the image, I need the Offset X and Offset Y. Is there any property which gives me this information?
Using plain Javascript and the "mousedown" and "mousemove" event.
You can use offsetX and offsetY properties of the MouseEvent object.
document.addEventListener('mousedown', function(e) {
console.log(e.offsetX, e.offsetY);
});
the values you want are offsetX and offsetY values
document.addEventListener('click', function(e) {
const element = document.getElementById("child");
const offsetX = (e.clientX - element.offsetLeft)
const offsetY = (e.clientY - element.offsetTop)
}
Related
I have a <canvas> element that spans the width and height of my webpage, like a background. It has interactive elements that rely on mouse coordinates. When the canvas was in it's own block (i.e. nothing over it) the interactive elements worked fine. But now that it's got divs over it it's not picking up any of the mouse interactions.
Below is my javascript code for the mousemove stuff. Why would items on top affect it picking up mouse xy coordinates, and how do I fix it?
var mouse = {x:-100,y:-100};
var mouseOnScreen = false;
canvas.addEventListener('mousemove', MouseMove, false);
canvas.addEventListener('mouseout', MouseOut, false);
var MouseMove = function(e) {
if (e.layerX || e.layerX == 0) {
//Reset particle positions
mouseOnScreen = true;
mouse.x = e.layerX - canvas.offsetLeft;
mouse.y = e.layerY - canvas.offsetTop;
}
}
var MouseOut = function(e) {
mouseOnScreen = false;
mouse.x = -100;
mouse.y = -100;
}
var update = function(){
var i, dx, dy, sqrDist, scale;
//...... this chunk is the only part of the function that references the mouse
dx = parts[i].x - mouse.x;
dy = parts[i].y - mouse.y;
sqrDist = Math.sqrt(dx*dx + dy*dy);
if (sqrDist < 20){
parts[i].r = true;
}
.....
}
If you don't need the top divs to be mouse-aware then set their CSS pointer-events:none; and the mouse events will filter down to your canvas underneath. Questioner needs responsive buttons placed over the canvas.
If the top divs do need to respond to mouse events, you might have to listen for mouse events on the window and convert those to canvas coordinates that your app can respond to.
You can listen for mousemove events on the window and get all moves -- even when over button elements. Also listen for mouseout events on the window. Since the canvas spans the window, you know mouseout happens when mouseevent.clientX & mouseevent.clientY report the coordinates are outside the window
Solved the issue with this code I found from another SO answer that I modified a bit.
function simulate(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousemove", true, true, window,
0, e.screenX, e.screenY, e.clientX, e.clientY, false, false, false, false, 0, null);
canvas.dispatchEvent(evt);
console.log("Emulated.");
}
$("body > section, body > header").each(function(){
this.addEventListener("mousemove", simulate);
});
Also, as a side note. Changed original layerX and layerY in mouse code to offsetX and offsetY to work in firefox (in addition to all other browsers)
I am trying to drag and drop a element based on mouse coordinates. Its working fine in chrome and IE but not working in firefox.
Below is what I have tried:
function createShape(event)
{
var stageContainer = $(".mainArea");
var stageOffset = stageContainer.offset();
clientX = event.clientX;
clientY = event.clientY;
offsetX = stageOffset.left;
offsetY = stageOffset.top;
x = clientX - offsetX; // works in chrome and IE
y = clientY - offsetY; // works in chrome and IE
//Firefox
var offX = (event.offsetX || event.pageX - $(event.target).offset().left);
var offY = (event.offsetY || event.pageY - $(event.target).offset().top);
layerX = event.layerX;
layerY = event.layerX;
screenX = event.screenX;
screenY = event.screenY;
pageX = event.pageX;
pageY = event.pageY;
e = jQuery.event.fix(event);
var target = event.target || event.srcElement;
//Right now this is working but x and y are not exactly correct
x = screenX + offsetX
y = screenY + offsetY
Doesn't work in firefox
ClientXY return 0,0
LayerXY return largest number like 173839,173839
pageX and pageY returns 0,0
element.offset().left returns 70 always
element.offset().top returns 63 always
createRect(x, y); // creating element on dragend with x and y coordinates on dragend
}
How do I get drag end mouse coordinates?
Sadly, Firefox does not fill pageX and pageY properties on drag events. The relevant bug report is open since 2009 and it doesn't look like it is getting fixed anytime soon. The common solution is to listen for dragover event on the parent element (although it makes it difficult to detect which element is being dragged) or detect the position of the element being dragged in some other way.
I want to create an element and then have that element be immediately bound to the cursor. I have tools to move the element, but I don't know how to bind them to the cursor without having to click the element. I thought about simulating the mousedown() event, but I don't know how to do it.
For context, my ultimate goal is to create a line with user defined endpoint. The user clicks a point and 2 small black circles are created. One as a reference point the the first click and the other to be attached to the cursor with a path connect the 2 points. Once the user clicks another point, both small black circles with disappear and only the line will remain.
Any ideas?
Thanks to #Joan Charmant for pointing me in the right direction. Here's my solution thus far. $('#paper') is my canvas and tempPoint is the circle I created to bind to cursor movement.
$("#paper").mousemove(function (event)
{
if(firstLinePointSelected && tempPoint!=null)
{
if (!event) var event = window.event;
var x=0, y=0;
if (event.pageX || event.pageY)
{
x = event.pageX;
y = event.pageY;
}
else if (event.clientX || event.clientY)
{
x = event.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// subtract paper coords on page
tempPoint.attr("cx", x - $('#paper').offset().left);
tempPoint.attr("cy", y - $('#paper').offset().top);
}
});
I've got some very simple code that attempts to attach an event listener and call a function on mousemove, so that I can find the mouse position within a canvas element:
canvas = document.getElementsByTagName('canvas');
canvas.addEventListener('mousemove', on_canvas_move, false);
function on_canvas_move(ev) {
var x = ev.clientX - canvas.offsetLeft;
var y = ev.clientY - canvas.offsetTop;
$('#status').html(x +', '+ y);
}
However I get the error: Uncaught TypeError: Object # has no method 'addEventListener'
What exactly is going on here?
getElementsByTagName() returns a nodeList (like an array of DOM objects) so you need to designate which element in that nodeList you want to add the listener to.
And secondly, your event handler on_canvas_move() also has the same issue as canvas.offsetLeft would be trying to read the .offsetLeft property on the nodeList, not on the DOM element. That would give you an undefined value and trying to do math with undefined gives you NaN.
To add just one:
canvas = document.getElementsByTagName('canvas');
canvas[0].addEventListener('mousemove', on_canvas_move, false);
function on_canvas_move(ev) {
var x = ev.clientX - this.offsetLeft;
var y = ev.clientY - this.offsetTop;
$('#status').html(x +', '+ y);
}
Or, to add all of them:
canvas = document.getElementsByTagName('canvas');
for (var i = 0; i < canvas.length; i++) {
canvas[i].addEventListener('mousemove', on_canvas_move, false);
}
function on_canvas_move(ev) {
var x = ev.clientX - this.offsetLeft;
var y = ev.clientY - this.offsetTop;
$('#status').html(x +', '+ y);
}
document.getElementsByTagName() returns you an array - you should either loop it and bind the listener, or point to the element you need:
document.getElementsByTagName('canvas')[0].addEventListener( ... )
An advice - when you don't know what's going on, figure it yourself by printing out stuff to console - console.log(canvas) would have told you.
This question already has answers here:
How do I get the coordinates of a mouse click on a canvas element? [duplicate]
(22 answers)
Closed 3 years ago.
Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.
The accepted answer will not work every time. If you don't use relative position the attributes offsetX and offsetY can be misleading.
You should use the function: canvas.getBoundingClientRect() from the canvas API.
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
}, false);
Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.
This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.
Something like this should work for those two:
function mouseMove(e)
{
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
/* do something with mouseX/mouseY */
}
Also note that you'll need CSS:
position: relative;
set to your canvas tag, in order to get the relative mouse position inside the canvas.
And the offset changes if there's a border
I'll share the most bulletproof mouse code that I have created thus far. It works on all browsers will all manner of padding, margin, border, and add-ons (like the stumbleupon top bar)
// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
// takes an event and a reference to the canvas
function getMouse = function(e, canvas) {
var element = canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset. It's possible to cache this if you want
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar (like the stumbleupon bar)
// This part is not strictly necessary, it depends on your styling
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object with x and y defined
return {x: mx, y: my};
}
You'll notice that I use some (optional) variables that are undefined in the function. They are:
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
// Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
// They will mess up mouse coordinates and this fixes that
var html = document.body.parentNode;
htmlTop = html.offsetTop;
htmlLeft = html.offsetLeft;
I'd recommend only computing those once, which is why they are not in the getMouse function.
For mouse position, I usually use jQuery since it normalizes some of the event attributes.
function getPosition(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - $(targ).offset().left;
var y = e.pageY - $(targ).offset().top;
return {"x": x, "y": y};
};
// now just make sure you use this with jQuery
// obviously you can use other events other than click
$(elm).click(function(event) {
// jQuery would normalize the event
position = getPosition(event);
//now you can use the x and y positions
alert("X: " + position.x + " Y: " + position.y);
});
This works for me in all the browsers.
EDIT:
I copied the code from one of my classes I was using, so the jQuery call to this.canvas was wrong. The updated function figures out which DOM element (targ) caused the event and then uses that element's offset to figure out the correct position.
GEE is an endlessly helpful library for smoothing out troubles with canvas, including mouse location.
Simple approach using mouse event and canvas properties:
JSFiddle demo of functionality http://jsfiddle.net/Dwqy7/5/
(Note: borders are not accounted for, resulting in off-by-one):
Add a mouse event to your canvas
canvas.addEventListener("mousemove", mouseMoved);
Adjust event.clientX and event.clientY based on:
canvas.offsetLeft
window.pageXOffset
window.pageYOffset
canvas.offsetTop
Thus:
canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
The original question asked for coordinates from the upper right (second function).
These functions will need to be within a scope where they can access the canvas element.
0,0 at upper left:
function mouseMoved(event){
var canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
0,0 at upper right:
function mouseMoved(event){
var canvasMouseX = canvas.width - (event.clientX - canvas.offsetLeft)- window.pageXOffset;
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
I'd use jQuery.
$(document).ready(function() {
$("#canvas_id").bind( "mousedown", function(e){ canvasClick(e); } );
}
function canvasClick( e ){
var x = e.offsetX;
var y = e.offsetY;
}
This way your canvas can be anywhere on your page, relative or absolute.
Subtract the X and Y offsets of the canvas DOM element from the mouse position to get the local position inside the canvas.