Reputation: 461
I have a canvas say 100 x 100
And I have inside 10, 10 X 10 rectangles, how can I easily find which rectangle the mouse is on, onclick.
So far I can get the column like so, my canvas has 20 x 10 rectangles?
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
var x = this.width / 5;
var y = this.height / 10;
if (mouseX - 1 < x) {
alert('1');
} else if (mouseX - 1 < x * 2) {
alert('2');
} else if (mouseX - 1 < x * 3) {
alert('3');
} else if (mouseX - 1 < x * 4) {
alert('4');
} else {
alert('5');
}
Is there an easier way than to do if elses?
Thanks
Upvotes: 0
Views: 94
Reputation: 8503
For a more general solution which avoids the if/elses:
var mousenow;
var unit_width = 10;
var unit_height = 10;
$("canvas").bind("mousemove", function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
var column = Math.floor(mouseX/unit_width);
var row = Math.floor(mouseY/unit_height);
mousenow = "Column: " + column +" Row: " + row;
});
$("canvas").bind("click", function(e){
e.preventDefault();
alert(mousenow);
});
Upvotes: 1
Reputation: 4233
Unfortunately, it is not possible to do use a switch on "ranges" in javascript (AFAIK). However, you could write a loop like this?
for(var i = 1; i <= 10; i++)
if( (mouseX < (10*i)) && (mouseX >= 10*(i-1)) )
alert(i);
This will loop through the squares and check each one (assuming there are only 10 horizontal ones). You could then use the same logic for checking each "row" of squares, if there turn out to be more. Hope this helps!
Upvotes: 0
Reputation: 18219
consider
coordX = Math.floor(mouseX / x);
coordY = Math.floor(mouseY / y);
Note that it's zero based.
Upvotes: 2