프로그래밍/자바스크립트

자바스크립트 - 문서객체를 이용한 글자 움직이기 예제

가카리 2014. 9. 6. 23:34
반응형

문서 객체 모델(DOM, Document Object Model)은 document 객체와 관련된 객체의 집합입니다.


문서 객체 모델을 사용하면 HTML 페이지에 태그를 추가 수정 제거 할 수 있습니다.


다음은 이 문서 객체 모델을 이용한 글자들의 움직임을 만든 예제입니다.

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

</head>

<!-- 보조 함수 -->

<script>

        

        //랜덤한 정수를 생성

        function nextRandomInteger(limit){

        return Math.round(Math.random() * limit);

        }

        

        //랜덤한 알파벳을 리턴

        var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        function randomAlphabet(){

        return alphabet.charAt(nextRandomInteger(25));

        }

        

        //양음으로 랜덤한 속도를 생성하는 함수

        function randomSpeed(maxSpeed){

        return Math.random() * maxSpeed - Math.random() * maxSpeed;

        }


</script>


<!-- 생성자 함수 -->

<script>

        //MovingText 생성자 함수

        var canvasWidth = 700;

        var canvasHeight = 400;

        

        function MovingText(){

        

        //위치와 속도 속성

        this.x = nextRandomInteger(canvasWidth);

        this.y = nextRandomInteger(canvasHeight);

        this.vx = randomSpeed(10);

        this.vy = randomSpeed(10);

        

        //문서 객체를 생성합니다.

        this.body = document.createElement('h1');

        this.body.innerHTML = randomAlphabet();

        this.body.style.position = 'absolute';

        

        //문서 객체를 document.body 추가합니다.

        document.body.appendChild(this.body);

        

        MovingText.prototype.move = function(){

        

        //범위 검사

        if(this.x < 0 || this.x > canvasWidth){

        this.vx *= -1;

        }

        if(this.y < 0 || this.y > canvasWidth){

        this.vy *= -1;

        }

        

        //이동

        this.x += this.vx;

        this.y += this.vy;

        

        //화면에 이동표시

        this.body.style.left = this.x + 'px';

        this.body.style.top = this.y + 'px';

        }

        }


</script>


<!-- window.onload -->

<script>

        window.onload = function(){

        

        //변수를 선언

        var movingTexts = [];

        

        //배열에 MovingText 객체 100개를 생성합니다.

        for(var i = 0; i < 100; i++){

        movingTexts.push(new MovingText());

        }

        

        //움직이기

        setInterval(function (){

        

        for(var i in movingTexts){

        movingTexts[i].move();

        

        }

        

        

        }, 1000/60);

        

        }


</script>

<body>

        

        

        

        

</body>

</html>











실행 화면


글자들이 랜덤으로 나와서 여기저기 움직입니다.




반응형