Innacurate Y Coordinates in Canvas - javascript

I'm testing getting the mouse position in a canvas in Javascript.
I decided to try something: I wanted to draw a rectangle at the position the mouse clicked on, but when I click anywhere on my canvas, the rectangle does draw at the X position of the cursor, but not on the Y.
I then went to see what the problem was, so I made it so that the coordinates of the mouse on the canvas were visible, and I got interesting results.
In short: it's telling my cursor's Y position was 0, even though it wasn't at the top of the canvas:
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById('status');
status.innerHTML = mouseX + ' | ' + mouseY;
});
ctx.canvas.addEventListener('click', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
item.drawItem(mouseX, mouseY);
});
Can anyone tell me why is this happening?

Use canvas.getBoundingClientRect().left instead of ctx.canvas.offsetLeft and canvas.getBoundingClientRect().top instead of ctx.canvas.offsetTop. See if this works?

Related

Get Mouse Pointer coordinates relative to some div

I am trying to get mouse pointer position on mousedown and mouseup event. There is a div named test and i want to get position when mousedown and mouseup happen within div area. And I am taking div as my surface so the mousedown and mouseup position should be related to div. I have a pdf inside that div so, the coordinates i get will help me to highlight the pdf.
I tried this, but its not working fine.
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
$("#test").mousedown(function(e){
var parentPosition = getPosition(e.currentTarget);
startX = e.clientX - parentPosition.x;
startY = (e.clientY - parentPosition.y)*2.5;
});
$("#test").mouseup(function(e){
var parentPosition = getPosition(e.currentTarget);
endX = e.clientX - parentPosition.x;
endY= (e.clientY - parentPosition.y)*2.5;
});
The coordinates of the mouse relative to the div are stored in the offsetX, offsetY properties of the event object
$("#someDiv").click(function(e){
var x = e.offsetX;
var y = e.offsetY;
});
So if you have a div with a width of 100 and a height of 50, and click exactly in the center of the div then
x = 50, y = 25
JSFiddle Demo

How do I make this function update the current mouse position?

I'm making a drawing pad, and I want the mouse location to update in an array as the mouse is dragged. Here is my code:
function penDown (x, y) {
isPenDown = true;
localPen.x = x;
localPen.y = y;
}
var X = [],
Y = [],
i = -1;
function penMove (x, y) {
if (isPenDown) {
++i;
X[i] = localPen.x;
Y[i] = localPen.y;
console.log("i is " + i + ", x is " + X[i] + ", y is " + Y[i]);
}
};
The console log shows that i is updating continuously when you move the mouse, but the X and Y coordinates of the mouse don't change - they just stay on the initial mouse location when you first press down the mouse.
Here is how I call penDown:
function pointerDownListener (e) {
// Retrieve a reference to the Event object for this mousedown event.
var event = e || window.event;
// Determine where the user clicked the mouse.
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Move the drawing pen to the position that was clicked
penDown(mouseX, mouseY);
}
function pointerMoveListener (e) {
var event = e || window.event; // IE uses window.event, not e
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Draw a line if the pen is down
penMove(mouseX, mouseY);
}
It might be, because your function penDown is only called once, so the values of x and y assigned to localPen won't change.

HTML5 Canvas Mouse Listener Coordinates Undefined

I'm attempting to take in mouse coordinates from a mouse listener but they are coming in undefined. The mouse listener is being added to the Canvas and the listener is triggering the onMouseMove function, however the event being passed doesn't seem to have any defined x or y coordinates for the mouse position.
I've tried the following variables: event.pageX, event.pageY, event.clientX, event.clientY, event.x, event.y
Any ideas on what I'm doing incorrectly to cause the mouse coordinates to come in undefined? Thanks for any help!
<script>
var boxes;
var canvas;
var context;
$(document).ready(function() {
canvas = document.getElementById("requirement_tree");
context = canvas.getContext("2d");
// Add mouse listener
canvas.addEventListener("mousemove", onMouseMove, false);
});
// Get the current position of the mouse within the provided canvas
function getMousePos(event) {
var rect = canvas.getBoundingClientRect();
if (event.pageX != undefined && event.pageY != undefined) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
console.log("X:" + x);
console.log("Y:" + y);
return {
X: x - rect.left,
Y: y - rect.top
};
}
function onMouseMove(event) {
var mousePos = getMousePos(canvas, event);
var message = 'Mouse position: ' + mousePos.X + ',' + mousePos.Y;
context.font = '10pt Arial'
context.fillStyle = 'black';
context.textAlign = 'left';
context.clearRect(0, 0, 200, 200);
context.fillText(message, 100, 100);
}
</script>
At least, error in handler for mouseMove event. Event object transmitted in second arguments of handler.
// ...
// Get the current position of the mouse within the provided canvas
function getMousePos(element, event) {
var rect = canvas.getBoundingClientRect();
// ...

Simple way to track mouse coordinates while moving over HTML5 canvas

Is there a simple way to get relative mouse coordinates while moving mouse over HTML5 canvas?
I found this:
function getMousePos(canvas, evt){
// get canvas position
var obj = canvas;
var top = 0;
var left = 0;
while (obj && obj.tagName != 'BODY') {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
// return relative mouse position
var mouseX = evt.clientX - left + window.pageXOffset;
var mouseY = evt.clientY - top + window.pageYOffset;
return {
x: mouseX,
y: mouseY
};
}
But it seems too heavy to me. Is there a reason using frameworks (like Kinetic) when working with canvas to simplify such things?
If you're not using your mousemove on your canvas use this:
$(function () {
canvas = document.getElementById('canvas');
canvas.onmousemove = mousePos;
});
function mousePos(e) {
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
You could position canvas absolutely and then remove while loop.
Ultimately, if canvas would not move, you could cache it's offset and then use cached value.
And to cover all cases: if canvas would have fixed position, you'll need not consider scrolling: pageXOffset, pageYOffset.

Tile Map Coordinates

I am have now this code: http://jsfiddle.net/DK67k/2/
In here is 2D tile map and when you click on tile you get coordinates on alert.
But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates.
Maybe anyone have idea how to fix this?
The canvas point (0,0) is at mouse coords (10,10), i think is due to parent of canvas has a padding area.
function mouseCheck(e) {
x = e.pageX-10;
y = e.pageY-10;
mouseX = Math.floor(x / 16);
mouseY = Math.floor(y / 16);
}
Blaus' answer is correct.
Though you might want to subtract the canvas offset left- and top position to make your canvas element available for dynamic positioning, and not relative to the 10px padding.
function mouseCheck(e) {
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
mouseX = Math.floor(x / 16);
mouseY = Math.floor(y / 16);
}

Categories