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:
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.
<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>
Do you like this article? Share it with your friends with this link: http://miloq.blogspot.com/2011/05/coordinates-mouse-click-canvas.html
ReplyDeleteThanks for reading!
Really nice tutorial. Thank you Manuel.
ReplyDeleteYou can follow me on Google+ at: http://gplus.to/miloq.
ReplyDeleteI 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.
ReplyDeleteFlocsy: yes, it's a common problem in Chrome, I hope that the future version this bug will be fixed! Thanks for comment!
ReplyDeleteThis works only if you are not altering the position of a canvas via div tags and CSS positioning.
ReplyDeleteThis is the problem I am currently having anybody know any solutions?
DeleteI had to use this in firefox:
ReplyDeletecanvas.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.
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
ReplyDeletelocalhost
DeleteThe 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.
ReplyDeleteI 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?
ReplyDeleteThanks in advance for the help!
Tested in Android and iOS, and worked perfectly for me.
ReplyDeleteThank you sooo much. It took me an hour with the firefox problem.^^
ReplyDeleteThank you for this. I've been looking for a while and could not find anything that works
ReplyDeleteI had problems with when the window scrolled down, to fix it I just added:
ReplyDeletex = x - window.pageXOffset;
y = y + window.pageYOffset;
After the: y -= canvas.offsetTop;
Works very well!
Thanks, exactly what I needed ! :)
ReplyDeleteAwesome man ! Your article helped me fix the bug with FF event handler. Keep it up!
ReplyDeleteHow can i use this script to show custom coordinates? what do i need to adjust?
ReplyDeleteThanks for the great post! Is this ok with mobile? Or do you have to use touch events?
ReplyDeletewhat if i have multiple elements inside canvas and i want to retrieve data out of it on clicking it?
ReplyDeleteCool!!!
ReplyDeleteYour the man :D
*you're
DeleteI would be really interested to know if it possible to do the same thing in a photoshop canvas??
ReplyDeleteI keep trawling the internet but don't seems to be able to find any definite info.
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
ReplyDeleteThanks dude
ReplyDeleteVery Cool! THankyou so much, I need this for my little Game on the Canvas ;)
ReplyDeleteThanks :) You are a prince
ReplyDeleteThanks a lot.. u rock mahn !! :)
ReplyDeletetotally awesome!
ReplyDeleteyou could also use this:
if(mouseX>=267&&mouseX<=358&&mouseY>=326&&mouseY<=375&&mouseIsPressed){Some Code}
You can just use e.offsetX and e.offsetY.
ReplyDeletei 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?
ReplyDeleteI 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.
ReplyDeletehow can i determinate a pivture cordinate in canvass ?
ReplyDeleteThank you, very helpful.
ReplyDeleteThank you,
ReplyDeleteI have solved my problem !
Thanks! Very Helpful!!!
ReplyDeleteIt works as long as there is no rotation applied on the canvas. Would you have a solution in that case?
ReplyDeleteIs this sentence grammatically correct? Any suggestions to improve?
ReplyDeletehtml shapes
Obrigado pelo trabalho.
ReplyDeleteAwsome. Exactly what I needed. Thanx alot.
ReplyDeleteThis 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.
ReplyDeleteWebsite for school uk
i really dislike that the website automatically downloads the html page without asking
ReplyDeleteNice blog. Thanks for sharing useful infomation.
ReplyDeletecanvas prints online
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.
ReplyDeletexpath in Java Selenium webdriver
ReplyDeleteNice blog. Thanks for sharing useful infomation.Nice blog. Thanks for sharing useful infomation.
ReplyDeleteauto clicker
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
ReplyDeleteyour computer information is a very nice. my mouse wont work
ReplyDeleteI am having trouble finding mouse price in pakistan for my lab.
ReplyDeleteI have heard that dell mouse is the best.
Please suggest which one shoud I purchase?
Hey did you check this link out
ReplyDeletevery More Informative blogs
Online Grocery Store Bismi
ReplyDeleteI 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.
ReplyDeleteTehran's nuclear program
ReplyDeleteWould-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 ...
دانلود زیرنویس فارسی سریال The Falcon and the Winter Soldier 2020
ReplyDeletegfoyyyyyyy
ReplyDeletegfooooorum
tepxxxxxxxxxx
afteahhhhh
oruzzzzzzzz
ilykityyyyyyy
ummypetaaaazzzzz
enretrievlllllle
xerfvvvvvvoru
gfoaaaaa
ReplyDeletegforunbbbbbbbbbbbbbbm
tepahhhhh
afteyaaaa
oruahhhhhh
ilykitaaaaaaag
ummypttttttet
enretriahhhheve
xerfahhhhhoru
gfoahhhhhh
ReplyDeletegforjjjjjum
tepahhhahh
afteahhhhhhh
ohaaaaru
ilykagggggt
ummahhhhypet
enrahhhhhetrieve
Really nice tutorial. Thank you Manuel. discountsau
ReplyDeleteReally nice tutorial.
ReplyDeletethanks for sharing
Nice sharing.
ReplyDeleteThanks
Great post.
ReplyDeleteThanks
Well Written Beautiful Post!
ReplyDeletehere is my post related to html canvas.
you may like.
Convert HTML to Canvas