I am currently using:
e.pageX - $("#canvas").offset().left
This is the only thing I am using Jquery for, so I would prefer to re-write this using just javascript.
What can I use to replace this?
The answer provided by N Rohler works well only in Internet Explorer (with some bugs prior to IE8 - but I guess it won't be a problem for you since you're using a canvas and pageX), and in Opera if the padding is 0, and in Safari/Chrome if the border width is 0 too. In Firefox, unfortunately, offsetX and offsetY are undefined.
http://www.quirksmode.org/dom/w3c_cssom.html#mousepos
Kaninepete, I think you should reconsider, for the sake of simplicity, the way of getting the mouse coordinates relatively to your canvas element. All you have to do is to calculate the position of the canvas, which is a pretty simple task using .getBoundingClientRect() (also, don't forget to add scroll offsets if necessary), and subtract it from pageX and pageY.
var x = e.offsetX,
y = e.offsetY;
Updated (again) for (correct) Firefox compatibility:
var rect = e.target.getBoundingClientRect();
var x = e.offsetX || e.pageX - rect.left - window.scrollX,
y = e.offsetY || e.pageY - rect.top - window.scrollY;
You can replace it by the below code
<canvas onmouseDown="mouseDown(event)" width="500" height="500"></canvas>
function mouseDown(e)
{
var x=e.clientX-canvas.offsetLeft;
var y=e.clientY-canvas.offsetTop;
}
Related
How can I apply a click at a specific position in a canvas? (using coordinates seems the most logical to me, but can't find any way to do it, any other idea is welcomed). Note that I do not have access to the code that creates the canvas.
EDIT: Some clarification, the canvas has multiple elements being drawn that i can't select with jquery but need to click them. I could find their coordinates manually and do some calculations, but every time i try to pass a click or mouse event into that position is not being taken as a real mouse click (the button that should be clicked, is not).
How about trying
canvas.on('click', function(e) {
// calculate x y coordinates on canvas
var x = e.pageX - $(this).offset().left,
y = e.pageY - $(this).offset().top;
// implement collision detection via the coordinates the element you want to click (assuming you know where it is)
if (y > <elementY> && y < <elementY> + <elementHeight>
&& x > <elementX> && x < <elementX> + <elementWidth>) {
alert('found it');
}
});
I have no time testing that snippet. If you know the x and y coordinates of your elements within your canvas, that code might just do the trick.
What I tried to do with that snippet is to simulate a bounding box via elmentY and elementY + elementHeight as well as elementX and elementX + elementWidth. If you know all those values, you can simply check whether the x and y values of your click event fall in that said box.
Edit
If you want to trigger a click event at a certain position, define the clickEvent beforehand and set the pageX and pageY attributes.
var e = new jQuery.Event("click");
e.pageX = 10;
e.pageY = 10;
$(<canvas>).trigger(e);
You might have to include the offset of your canvas in the calculations as well.
This question already has answers here:
Screen Coordinates of a element, via Javascript
(4 answers)
Closed 4 years ago.
Please note that neither the jQuery position function and Javascript's getBoundingClientRect do what I'm asking for.
I am trying to get the element's position relative to the top-left coordinates of the user's screen.
I am mainly looking to figure this out for Google chrome. I would appreciate any answer that can lead me down the right path.
Using the jQuery .offset() function, you can get the coordinates of the top-left of the browser page:
var offset = $("selector").offset();
Combining that with the Javascript window.screenX and window.screenY window properties, you can calculate the position of the element as an offset from the top/left of the screen:
var screenY = offset.top + window.screenX;
var screenX = offset.left + window.screenY;
Note that window.screenX and window.screenY are standard in most browsers, but IE versions 8 and prior use window.screenTop and window.screenLeft, instead. If you need compatibility with IE8 or earlier, make sure to take that into account.
Also note that you might need to account for the current scroll position, in which case, you would use the jQuery .scrollTop() and .scrollLeft() methods and subtract from the offset value.
Unfortunately, this will not take window borders or toolbars into account. To do that, you can capture a mouse move and store the mouse position, which is given in actual screen coordinates.
The core of this solution is the following, which installs a one-time-use mouse handler to determine the actual screen coordinates of the page:
var pageX;
var pageY;
window.onmousemove = setMouseCoordinates;
function setMouseCoordinates (e) {
window.onmousemove = null;
pageX = e.screenX - e.clientX;
pageY = e.screenY - e.clientY;
}
Then, you can use those stored values to calculate the offset of any Javascript element:
x = pageX + elem.offsetLeft;
y = pageY + elem.offsetTop;
or jQuery element:
x = pageX + elem.position().left;
y = pageY + elem.position().top;
Check out the fiddle to see it in action: https://jsfiddle.net/mgaskill/bpqzct3f/
I think HTMLElement.offSetLeft and HTMLElement.offSetTop is what you're looking for.
having trouble with a small issue which is affecting Internet Explorer (latest). In Firefox and Chrome, when I click the div the coordinates are 494, 438. In Internet Explorer, if I click in the same place I receive 371, 298.
My code:
$('body').on('click', '.map area', function(e)
{
var x = e.pageX - this.offsetLeft - 30;
var y = e.pageY - this.offsetTop - 80;
});
Any help would be very appreciated. If this is being caused by something other than the JS, let me know and I will gladly provide CSS, HTML etc.
Thanks in advance!
http://www.asifslab.com/reveal.js-master/Why%20does%20wind%20feel%20cold.html#/4
Why doesn't the drawing canvas work properly? The line drawn is away from the point clicked. However, if I use the canvas out of reveal.js it works perfectly. http://codepen.io/anon/pen/eEaKh
Also when the erase function is run, it leaves a white border outside. How do I fix these problems?
just change e.pageX to e.clientX and e.pageY to e.clientY because in your codepen account
canvas origin and page origin is almost at same place but in other it is not.
To calculate the mouse position you need to subtract the position of the canvas:
Here is one way of doing this (inside the event handler):
var rect = canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
Now your x and y will be relative to canvas.
Here's a copy/pasta of a small part of my paint app. Notice I'm using offsets of the canvas in my calculations. I also have a zoom function that scales the canvas, so taking into account that I added it to the calculation of the mouse cursor.
$('canvas').mousemove(function(e) {
// x and y are globals, x inits to null, mousedown sets x, mouseup returns x to null
if (x==null) return;
x = (100/$('#zoom').val())*(e.pageX - $(this).offset().left);
y = (100/$('#zoom').val())*(e.pageY - $(this).offset().top);
$('#debug').html(x+', '+y); // constantly update (x,y) position in a fixed div during debugging
});
I'm capturing mouse position like this
mouse_move: function(e)
{
mousePos.x = e.pageX - vr.o.context.canvas.offsetLeft;
mousePos.y = e.pageY - vr.o.context.canvas.offsetTop;
},
and it has worked like a dream in all modern browsers while in development, Even tested Wrapping the <canvas/> in a basic dom structure to make sure mouse position adjusted...
obviously now I'm putting it in the actual site it's not working...
You can see here http://jondavidjohn.com/projects/
the mouse position ends up quite a ways south of the actual cursor, anything specifically that could be causing this?
SOLUTION
mouse_move: function(e)
{
mousePos.x = e.offsetX;
mousePos.y = e.offsetY;
},
COPIED FROM: http://simonsarris.com/blog/510-making-html5-canvas-useful
Getting mouse coordinates on Canvas
Getting good mouse coordinates is a little tricky on Canvas. You could use offsetX/Y and LayerX/Y, but LayerX/Y is deprecated in webkit (Chrome and Safari) and Firefox does not have offsetX/Y.
The most bulletproof way to get the correct mouse position is shown below. You have to walk up the tree adding the offsets together. Then you must add any padding or border to the offset. Finally, to fix coordinate problems when you have fixed-position elements on the page (like the wordpress admin bar or a stumbleupon bar) you must add the ’s offsetTop and offsetLeft.
Then you simply subtract that offset from the e.pageX/Y values and you’ll get perfect coordinates in almost every possible situation.
// 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
CanvasState.prototype.getMouse = function(e) {
var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset
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
offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object (a hash) with x and y defined
return {x: mx, y: my};
}
Use e.offsetX and e.offsetY for now instead.
It actually gets more complicated when you introduce some other things, like margins and padding, but offsetX and offsetY will be much more accurate than what you've got to say the least.
I don't have my new "bulletproof-works-in-every-situation" mouse code on me right now, I can get that later for you if you think you'll need it.
edit: Derp! Thanks chopperdave for finally providing the code I forgot to add!