Search code examples
htmlcanvasposition

Getting the correct coordinates of a canvas touch event


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


Solution

  • 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