I've been diving into JavaScript for a new project and I could really use some guidance.
My current hurdle involves updating the outer variables xPosition
and yPosition
with the new positions generated by the getMousePosition()
function within the positionManager()
function, but unfortunately it's not working as expected.
After scouring various online resources (including this platform), it seems like the issue may be related to closures, scopes, and local variables, which still leave me a bit perplexed.
Edit1: Apologies for any confusion. What I meant was that the value of
var xPosition = 0;
isn't being replaced by the values from the positionManager()
function. The goal was for xPosition = mousePos.x
to take over, but it doesn't seem to be happening.
Edit2: Every time the mouse moves on the canvas, the getMousePosition
function captures the mouse coordinates. Subsequently, the positionManager
should update the topmost var xPosition
. However, despite these actions, the var xPosition
continues to display 0.
function mouseController(canvas, context) {
var xPosition = 0; // To be updated by values from positionManager.
var yPosition = 0; // ^
canvas.addEventListener("mousemove", positionManager);
canvas.addEventListener("mouseout", hideCoordinates);
canvas.addEventListener("click", drawWidget);
/**
*Gets the mouse position.
* @param canvas
* @returns x and y coordinates. Use (VARIABLE NAME).x and (VARIABLE NAME).y
*/
function getMousePosition(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((event.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
y: Math.round((event.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
};
}
/**
* Manages and directs the mouse positions received from getMousePosition().
*
* @param event
*/
function positionManager(event) {
var mousePos = getMousePosition(canvas, event);
// Formats a message that shows the coordinates.
var mouseCoordinates = 'Coordinates: ' + mousePos.x + ',' + mousePos.y;
xPosition = mousePos.x; // Update the global variable with this new value.
yPosition = mousePos.y;
console.log("positionManager xPosition: " + xPosition); // Operates correctly, showing new coordinates each time the mouse moves.
// Sends the message to be displayed.
displayCoordinates(mouseCoordinates);
}
console.log("global var xPosition: " + xPosition); // Still showing 0 even after positionManager
}