-1

I've got a HTML Canvas with an image in it and I would like to get mouse coordinates where user clicked within the image.

I can do this in a way, that I get mouse coordinates starting from top-left corner of the canvas, but I need to use top-left corner of the image itself as [0,0] point.

I am working with this example http://phrogz.net/tmp/canvas_zoom_to_cursor.html

thanks

Igor
  • 592
  • 2
  • 9
  • 31
  • Look at the solutions on these questions: http://stackoverflow.com/questions/3824332/mouse-position-relative-to-div or http://stackoverflow.com/questions/4848310/getting-mouse-position-with-javascript-within-canvas, it will be something similar, just changing the code a little – Alvaro Montoro Feb 13 '15 at 16:15
  • Do you know the width and the height of the image and of the canvas? – Jonas Grumann Feb 13 '15 at 16:16
  • @JonasGrumann yes, I know the dimensions – Igor Feb 13 '15 at 16:40
  • @AlvaroMontoro hmm, the main problem is that the image may be transformed in different ways, I don't think the questions you mentioned consider this in any way – Igor Feb 13 '15 at 16:43

1 Answers1

-1

The context.translate(x,y) command does exactly what you're asking for.

context.translate will move the origin of the canvas to the x,y coordinates given to it. So if x,y is the top left corner of the "hit" image, then you can make x,y the origin (effectively 0,0) using context.translate(x,y)

You don't present code, but I assume that you have already:

  • determined where the user clicked the mouse,

  • determined if the user clicked the image by hit-testing the mouse coordinate against the bounds of the image,

  • have available the x,y where you originally drew that image on the canvas

To illustrate, if you context.translate(imageLeftX,imageTopY) and a then fillRect(0,0,1,1) will draw a rectangle in the top left corner of the image.

markE
  • 102,905
  • 11
  • 164
  • 176