3

I am facing problems getting the correct coordinate of touch event. This is my markup

<div class="board">
<canvas width="595" height="595" id="bgCanvas"></canvas>
<canvas width="595" height="595" id="liCanvas"></canvas>
</div>

The CSS

.board{
 width:595px;
 height:595px;  
 position:absolute;
 display:block;
 left:21px;
 top:230px;
}
.board canvas{
position:absolute;
}

and the code, note that I have I already added touch event listener to liCanvas

evX= ev.targetTouches[0].pageX- liCanvas.offsetLeft 

but I'm not getting the right value, I mean I want evX=0 when I touch on the upper left corner of the canvas. Please help me

Lamia Mehreen
  • 759
  • 1
  • 8
  • 15

3 Answers3

7

The accepted solution work when arborescence is simple, but for some cases (mine for example) when there can be multiple nested scrolling parents it won't work as intended.

Another solution which work in every cases I have see so far is to use

var rect = canvas.getBoundingClientRect();
evX = ev.targetTouches[0].pageX - rect.left,
Arfost
  • 506
  • 1
  • 4
  • 16
5

offsetLeft gives the position of element with respect to your board but you want it with respect to body so use the code given below

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

evX= ev.targetTouches[0].pageX- getOffsetLeft(liCanvas); 

Reference

Community
  • 1
  • 1
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
2

I think you should use getBoundingClientRect and clientX and clientY (instead of pageX and pageY) to extract the event coordinates and offset coordinates. Because they are all relative to the viewport, the event coordinates on the canvas can be correctly computed.

For the source code and the demo, please check out my example.

Lei Mao
  • 33
  • 1
  • 5