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>

63 comments:

  1. Really nice tutorial. Thank you Manuel.

    ReplyDelete
  2. 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
  3. Flocsy: yes, it's a common problem in Chrome, I hope that the future version this bug will be fixed! Thanks for comment!

    ReplyDelete
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. Tested in Android and iOS, and worked perfectly for me.

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

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

    ReplyDelete
  12. 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
  13. Thanks, exactly what I needed ! :)

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

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

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

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

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

    ReplyDelete
  19. 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
  20. 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
  21. Very Cool! THankyou so much, I need this for my little Game on the Canvas ;)

    ReplyDelete
  22. Thanks :) You are a prince

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

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

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

    ReplyDelete
  26. 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
  27. 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
  28. how can i determinate a pivture cordinate in canvass ?

    ReplyDelete
  29. Thank you, very helpful.

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

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

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

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

    ReplyDelete
  34. 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
  35. i really dislike that the website automatically downloads the html page without asking

    ReplyDelete
  36. 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
  37. Nice blog. Thanks for sharing useful infomation.Nice blog. Thanks for sharing useful infomation.
    auto clicker

    ReplyDelete
  38. There are dissertation sheets together with the web site while you turned out to be obviously believed in the blog page. include javascript file in html

    ReplyDelete
  39. I am having trouble finding mouse price in pakistan for my lab.
    I have heard that dell mouse is the best.
    Please suggest which one shoud I purchase?

    ReplyDelete
  40. I am having some of Uk boden promo code 25% through you can enjoy this offers and can send gifts With Discount Coupon to any of your lover who is very angry with you.

    ReplyDelete
  41. Tehran's nuclear program

    Would-be medical exec from Iran barred from Canada over alleged ties to Tehran's nuclear program. Ramin Fallah was labeled a security threat because he ...

    ReplyDelete
  42. Really nice tutorial. Thank you Manuel. discountsau

    ReplyDelete
  43. Really nice tutorial.
    thanks for sharing

    ReplyDelete
  44. Well Written Beautiful Post!
    here is my post related to html canvas.
    you may like.
    Convert HTML to Canvas

    ReplyDelete