0

I've been struggling to get this code working. Basically, I want the user to be able to click anywhere inside of the canvas, and the coordinates at the clicked point will be where the rectangle gets drawn. However, the code I have places the rectangles at totally unexpected points along the canvas. I checked the values in Firebug and they seemed to be accurate based on where I clicked inside the canvas, so I'm not sure why the rectangles are not getting drawn at the correct points. Maybe there is some other mistake going on that I am not seeing though, so any help or input would be appreciated. I've posted the relevant code below.

I should also note that the canvas element is inside the div with id='container'.

 $('#container').click(function (e) {
     var offset=$(this).offset();
     var x=(e.pageX - offset.left);
     var y=(e.pageY - offset.top);

     ctx.fillStyle='#FF0000'; //color red
     ctx.fillRect(x,y,10,10); //draw 10 x 10 rectangle starting at x,y
     });
user3394907
  • 131
  • 3
  • 8
  • 2
    possible duplicate of [How do I get the coordinates of a mouse click on a canvas element?](http://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element) – Etheryte Jul 24 '15 at 00:15

2 Answers2

0

pageX/Y gets the x/y coordinate of the page (think 100, 200). Let's say your canvas is positioned at (100,100) on the page. When you're graphing the point, you're saying "Graph a point at 100,200 IN RELATION TO THE CANVAS. That would mean you are trying to graph a point at (200,300) instead of (100,200) linke you want. You need to get your x/y in relation to the canvas, like so:

var x = event.offsetX !== undefined ? event.offsetX : event.layerX;
var y = event.offsetY !== undefined ? event.offsetY : event.layerY;
perennial_
  • 1,798
  • 2
  • 26
  • 41
0

If you only want to add a click event on the canvas then it's better to use

$("#myCanvas").click(function(e){
});

If you use myCanvas instead of container then $(this) would refer to the canvas and you get the position of the mouse relative to the canvas. It is because you use the container div that the variable offset is wrong.