Reputation: 53
canvas.addEventListener("mousedown", getPosition, false);
function getPosition(event)
{
var x = event.x;
var y = event.y;
var canvas = document.getElementById("canvas");
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
alert("x:" + x + " y:" + y);
}
This simple function will get me the coordinates of where the mouse is clicked, it currently works on right and left click but i only want it to work if it's right click, some kind of if rightClicked:
Upvotes: 1
Views: 41
Reputation: 191976
Use the contextmenu
event:
canvas.addEventListener("contextmenu", getPosition, false);
function getPosition(event) {
event.preventDefault();
var x = event.x;
var y = event.y;
var canvas = document.getElementById("canvas");
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
console.log("x:" + x + " y:" + y);
alert("x:" + x + " y:" + y);
}
canvas {
background: red;
}
<canvas id="canvas"></canvas>
Upvotes: 3
Reputation: 68933
The browser interprets the 'right click' as 'context menu'. Hence, your event handler needs to be bound to the contextmenu
event.
Try:
canvas.addEventListener("contextmenu", getPosition, false);
canvas.addEventListener("contextmenu", getPosition, false);
function getPosition(event){
var x = event.x;
var y = event.y;
var canvas = document.getElementById("canvas");
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
alert("x:" + x + " y:" + y);
}
canvas {
background: green;
}
<canvas id="canvas"></canvas>
Upvotes: 1