Za Hirah
Za Hirah

Reputation: 43

How to get canvas cursor click coordinates

Hi i have this function that I found on this website.

function getCursorPosition(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y);
}

My question is, how do I pass an event as an argument. I want to call this function inside the canvas click event.

document.getElementById('puzzle').onclick = function(e) {
  //Call it here
};

Upvotes: 2

Views: 930

Answers (1)

Douwe de Haan
Douwe de Haan

Reputation: 6646

Guessing your canvas has an ID puzzle:

document.getElementById('puzzle').onclick = function(e) {
    getCursorPosition(this, e)
};

The event is passed to the function as e (which is almost always short for event).

Upvotes: 4

Related Questions