Javascript&Jquery

문서객체를 이용한 움직임 구현

알 수 없는 사용자 2012. 3. 13. 00:01

문서객체를 아래처럼 자바스크립트를 이용해서 동적인 효과를 구현할수 있따.
이걸 실행시키면 @를 가운데 두고, 0 *가 막 원을 그리면서 빙빙돈다

html 코드는 이렇게

@

0

*


자바스크립트소스는 이렇게

//문서객체를 사용한 움직임 구현
window.onload =function(){
	//문서객체를 가져오고 설정합니다
	var sun =document.getElementById('sun');
	var earth = document.getElementById('earth');
	var moon = document.getElementById('moon');
	
	sun.style.position ='absolute';
	earth.style.position ='absolute';
	moon.style.position ='absolute';
	
	sun.style.left =250 +'px';
	sun.style.top =200+'px';
	
	//변수를 선언합니다.
	var earthAngle = 0;
	var moonAngle = 0;
	
	//애니메이션을 시작합니다.
	setInterval(function(){
		//각도를 사용해 지구와 달의 좌표를 구합니다.
		var earthLeft = 250 +150 *Math.cos(earthAngle);
		var earthTop = 200 + 150*Math.sin(earthAngle);
		var moonLeft = earthLeft +50*Math.sin(moonAngle);
		var moonTop = earthTop +50*Math.sin(moonAngle);
		
		// 위치를 이동합니다.
		earth.style.left =earthLeft + 'px';
		earth.style.top = earthTop + 'px';
		moon.style.left =moonLeft +'px';
		moon.style.top = moonTop + 'px';
		
		//각도를 변경합니다.
		earthAngle +=0.1;
		moonAngle +=0.3
	}, 1000/30);
};