Search code examples
javascriptimagegetcoordinate

How to get pixel's index from image in javascript


I wanna make the ball bounce when it hit the board. So I have to get the board pixels to make it bounce when the ball hit the board. I tried this way but it didn't works. Here is my code Javascript code

var xboard = document.getElementById(board)
var movx = parseInt(xboard.style.left)

Image code

<img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline border=0 hspace=0 src="design/board.gif">

When I tried to get the pixels by

alert(movx)

It said "Undefined" at the alert box. Could anyone help me?


Solution

  • This method gives you the coordinates of control passed

    <img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline border=0 hspace=0 src="design/board.gif">
    
    function findPos(obj){
    var curleft = 0;
    var curtop = 0;
    
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
           } while (obj = obj.offsetParent);
    
        return {X:curleft,Y:curtop};
    }
    }
    
    findPos(document.getElementById('board'));
    alert(curleft);
    alert(curtop);
    

    For more details here