How do I assign mousePos.x to a global variable when clicked

How do I assign mousePos.x to a global variable when clicked
0

#1

So, I’ve managed to pull some code that allows me to click anywhere in the <canvas> and console.log() my X and Y positions, I can’t for the life of me though seem to assign them to global variables that I can use later in my code.

Any ideas, gratefully received. Currently just have this set up to console.log(mousePos.x)

How do I assign mousePos.x to a global variable


#2
var x;
var y;

function getMousePos(canvas, evt) {
  x = evt.clientX - rect.left;
  y = evt.clientY - rect.top;
}

Honestly, I think the way you have it working now is superior, but the above does assign globals.


#3

Thanks for your response , struggling to implement this though into the code so that when the mouse is clicked I can grab var x or var y to use later.


#4

You could actually copy and paste that into your code, replacing the current getMousePosition. What is it that you’re trying to accomplish?