-2

I have a canvas in html:

<canvas id="canvas" width="450" height="450"></canvas>

That I made nine equally sized squares in. I would like to see what square I have clicked as an alert function. How would I do that?

Full Code is here: https://jsfiddle.net/ckd6g1ac/1/

Sorry, I do not have any code relevant to my problem in the JSFiddle, but I have no clue on how to start writing it.

Thanks!

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Harshul Sahni
  • 140
  • 1
  • 1
  • 10

1 Answers1

1

This is your onclick function:

$("#canvas").click(function(e) {
  var yNames = ['upper', 'middle', 'lower'],
    xNames = ['left', 'middle', 'right'];
  alert(('The '
    + yNames[Math.floor((e.offsetY * 3) / canvas.height)] + '-'
    + xNames[Math.floor((e.offsetX * 3) / canvas.width)] + ' box was clicked.')
      .replace('middle-middle', 'middle'));
});

Also you had a semantic error in your loop: it should be i<9 instead of 1<9.

offsetX and offsetY were used because these measure the offset from the element itself, which means that it doesn’t matter where the canvas is on the page.

Working JSFiddle.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75