Get the coordinates of a mouse click on Canvas in Javascript

When you are working with the canvas element in Javascript sometimes you need to interact with the user. You can interact with the keyboard, but it's more interesting using the mouse events. If you use the last method there's a problem, you can't use mouse events with the objects that are in the canvas element. You need to get the coordinates of a mouse click on a canvas element.

This is the code I use to get the coordinates:

canvas.addEventListener("mousedown", getPosition, false);

function getPosition(event)
{
  var x = event.x;
  var y = event.y;

  var canvas = document.getElementById("canvas");

  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;

  alert("x:" + x + " y:" + y);
}

This code works in every browser except in Firefox. In this browser, it's necessary to use other method to get the coordinates . The source code of the demo solves this problem.

Demostration

Click with your mouse on the black screen:

Source code of the demostration

To try the demo, copy this code and paste it into a text editor. Then save it as example.html and, finally, open the file with a browser.

<!doctype html>

<html>
  <head>
    <title>Get the coordinates on canvas</title>
    <meta charset="utf-8" />

    <style type="text/css">

      #canvas{background-color: #000;}

    </style>

    <script type="text/javascript">

      document.addEventListener("DOMContentLoaded", init, false);

      function init()
      {
        var canvas = document.getElementById("canvas");
        canvas.addEventListener("mousedown", getPosition, false);
      }

      function getPosition(event)
      {
        var x = new Number();
        var y = new Number();
        var canvas = document.getElementById("canvas");

        if (event.x != undefined && event.y != undefined)
        {
          x = event.x;
          y = event.y;
        }
        else // Firefox method to get the position
        {
          x = event.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = event.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }

        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;

        alert("x: " + x + "  y: " + y);
      }

    </script>

  </head>

  <body>
    <canvas id="canvas" width="640" height="360"></canvas>
  </body>
</html>

45 comments:

  1. Do you like this article? Share it with your friends with this link: http://miloq.blogspot.com/2011/05/coordinates-mouse-click-canvas.html

    Thanks for reading!

    ReplyDelete
  2. Really nice tutorial. Thank you Manuel.

    ReplyDelete
  3. I have a problem, and this demo reproduces it as well. In Chrome I can click 1 or even 2 pixels above the black area and I'll get the event with Y=2 or 1.

    ReplyDelete
  4. Flocsy: yes, it's a common problem in Chrome, I hope that the future version this bug will be fixed! Thanks for comment!

    ReplyDelete
  5. This works only if you are not altering the position of a canvas via div tags and CSS positioning.

    ReplyDelete
    Replies
    1. This is the problem I am currently having anybody know any solutions?

      Delete
  6. I had to use this in firefox:
    canvas.onmousedown = function(e) {
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
    }

    This e.offsetX/e.offsetY worked in chrome, and for chrome-only games, this is what I use. Hope somebody else finds this interesting. e.x did not seem to work in some browsers either.

    ReplyDelete
  7. This e.offset X /e.offset Y worked in chrome, and for chrome-only games, this is what I use. Hope somebody else finds this interesting. e.x did not seem to work in some browsers either

    ReplyDelete
  8. The event.x/y method does not work correctly in IE 9. When you minimize the browser so that only one quarter of the canvas is visible and then scroll to the right lower corner of the canvas, wrong coordinates are shown (it seems that only the visible part of the canvas is taken into account). The 'Firefox' method keeps working fine, also in Explorer when I disable the x/y method.

    ReplyDelete
  9. I am trying to use this method for getting the position of a mouse event inside an image regardless of how the user has zoomed in or out (Which this method accomplishes successfully!) Awesome... but my issue is that I need the method to work without using canvases as I am trying to have a website available to everyone - ie users without canvas interaction included. Is there anyway to get accomplish this without using canvases?

    Thanks in advance for the help!

    ReplyDelete
  10. Tested in Android and iOS, and worked perfectly for me.

    ReplyDelete
  11. Thank you sooo much. It took me an hour with the firefox problem.^^

    ReplyDelete
  12. Thank you for this. I've been looking for a while and could not find anything that works

    ReplyDelete
  13. I had problems with when the window scrolled down, to fix it I just added:
    x = x - window.pageXOffset;
    y = y + window.pageYOffset;
    After the: y -= canvas.offsetTop;
    Works very well!

    ReplyDelete
  14. Thanks, exactly what I needed ! :)

    ReplyDelete
  15. Awesome man ! Your article helped me fix the bug with FF event handler. Keep it up!

    ReplyDelete
  16. How can i use this script to show custom coordinates? what do i need to adjust?

    ReplyDelete
  17. Thanks for the great post! Is this ok with mobile? Or do you have to use touch events?

    ReplyDelete
  18. what if i have multiple elements inside canvas and i want to retrieve data out of it on clicking it?

    ReplyDelete
  19. Cool!!!
    Your the man :D

    ReplyDelete
  20. I would be really interested to know if it possible to do the same thing in a photoshop canvas??
    I keep trawling the internet but don't seems to be able to find any definite info.

    ReplyDelete
  21. I wil b rily intrusted 2 no if it iz pausible 2 do teh saem thang in paint? i is steel searching net bart fine narthing

    ReplyDelete
  22. Very Cool! THankyou so much, I need this for my little Game on the Canvas ;)

    ReplyDelete
  23. Thanks :) You are a prince

    ReplyDelete
  24. Thanks a lot.. u rock mahn !! :)

    ReplyDelete
  25. totally awesome!
    you could also use this:
    if(mouseX>=267&&mouseX<=358&&mouseY>=326&&mouseY<=375&&mouseIsPressed){Some Code}

    ReplyDelete
  26. You can just use e.offsetX and e.offsetY.

    ReplyDelete
  27. i have the same problem but little different our requirement is get the coordinate and page number in pdf while user select text . so pls help me how can i do this?

    ReplyDelete
  28. I have different problem.I have to get the (x,y) coordinate of image which is in canvas and i moving the image position from the mouse.Any help will be appreciated.

    ReplyDelete
  29. how can i determinate a pivture cordinate in canvass ?

    ReplyDelete
  30. Thank you, very helpful.

    ReplyDelete
  31. Thank you,
    I have solved my problem !

    ReplyDelete
  32. It works as long as there is no rotation applied on the canvas. Would you have a solution in that case?

    ReplyDelete
  33. Is this sentence grammatically correct? Any suggestions to improve?
    html shapes

    ReplyDelete
  34. Awsome. Exactly what I needed. Thanx alot.

    ReplyDelete
  35. This content creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this. Thanks.
    Website for school uk

    ReplyDelete
  36. i really dislike that the website automatically downloads the html page without asking

    ReplyDelete
  37. I have found this article to be not only educative but also entertaining. I will bookmark this site and visit it occasionally to read both new and old articles. I will also be recommending this site to our professional writers who have written articles such as How to Write a Good Research Paper.

    ReplyDelete