Using Javascript to find the coordinates on an image

In a web application that works with images it is useful to be able to allow the user to select a point on an image. The example here shows how this can be done using Javascript. We have a more detailed example with downloadable code that allows the user to select two points and draws a rectangle.

Click on the image to get the coordinates.

X:

Y:

The Javascript code

The following code is in the page header. The GetCoordinates function uses the window.event method to find the coordinates of the mouse when it is clicked. It also needs to take into account any scrolling and the position of the image inside the document so that the coordinates are always relative to the top left of the image. The FindPosition function finds the position of the image tag within the page. Different browsers define the position of an element in slightly different ways but this method will work in both Internet Explorer and Firefox.

<script type="text/javascript">
<!--

function FindPosition(oElement)
{
  if(typeof( oElement.offsetParent ) != "undefined")
  {
    for(var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent)
    {
      posX += oElement.offsetLeft;
      posY += oElement.offsetTop;
    }
      return [ posX, posY ];
    }
    else
    {
      return [ oElement.x, oElement.y ];
    }
}

function GetCoordinates(e)
{
  var PosX = 0;
  var PosY = 0;
  var ImgPos;
  ImgPos = FindPosition(myImg);
  if (!e) var e = window.event;
  if (e.pageX || e.pageY)
  {
    PosX = e.pageX;
    PosY = e.pageY;
  }
  else if (e.clientX || e.clientY)
    {
      PosX = e.clientX + document.body.scrollLeft
        + document.documentElement.scrollLeft;
      PosY = e.clientY + document.body.scrollTop
        + document.documentElement.scrollTop;
    }
  PosX = PosX - ImgPos[0];
  PosY = PosY - ImgPos[1];
  document.getElementById("x").innerHTML = PosX;
  document.getElementById("y").innerHTML = PosY;
}

//-->
</script>

The following code is placed inside the HTML body. The image needs an ID which is used in the code. The Javascript defines the function that will run when the mouse down event fires. The span blocks are used to display the coordinates.

<img id="myImgId" alt="" src="red.gif" width="400" height="300" />

<script type="text/javascript">
<!--
var myImg = document.getElementById("myImgId");
myImg.onmousedown = GetCoordinates;
//-->
</script>

<img src="red.gif" width="400" height="300" alt="" id="myImgId" />
<p>X:<span id="x"></span></p>
<p>Y:<span id="y"></span></p>

Another example shows how to use this technique with csImageFile to position text on an image.

Cookies

This site uses cookies for functionality, traffic analysis and for targeted advertising. Click the Accept button to accept our Cookie Policy. The Cookie Policy page offers configuration for a reduced set of cookies for this site.