자바스크립트

javascript - 이미지 좌표(위치) 구하기

안녕1999 2017. 2. 18. 23:30

left, top은 style에 있고, 문자열 형식이라서, parseInt(()함수를 사용해야 숫자가 된다.


x=parseInt(mg.style.left);




width, height는 이미지의 속성이며, 숫자이다. (parseInt()함수가 필요없다.)


w=img.width,

h=img.height,




function get_left(o){

return parseInt(o.style.left.replace('px',''));

}

function get_top(o){

return parseInt(o.style.top.replace('px',''));

}




이미지 너비, 높이 구하기 실패하는 이유 : body(이미지)가 로딩이 끝나야, 값을 얻을 수 있다.

사용할 이미지를 body에 넣고, 밑에서 자바스크립트로 처리한다.


<body style="margin:0;padding:0">

<img id=img1 src="img/1.JPG" style="visibility:hidden;position:absolute;left:0;top:16;">

...

<script type='text/javascript'>

...

img1_w=img1.width,

img1_h=img1.height;

...

//실제로 사용할 내용을 생성한다.

document.write("<img id='img1"+i+"' src='img/1.JPG'>");//처음 로딩된 내용은 모두 지워진다.

...

</script>

</body>