cgweb87
cgweb87

Reputation: 461

Canvas and getting the co ordinates based on a grid (via mouse x mouse y)

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

Answers (3)

minikomi
minikomi

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

SuperTron
SuperTron

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

qiao
qiao

Reputation: 18219

consider

coordX = Math.floor(mouseX / x);
coordY = Math.floor(mouseY / y);

Note that it's zero based.

Upvotes: 2

Related Questions