Cute Apple
본문 바로가기
개발/HTML&JS

html 객체와 class

by 미댕댕 2021. 3. 23.

 

 

 

 

 

 

 

 

 

 

 

 


 

작업 결과물 1

 

body, CSS, script 작업

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<script src='../js/lib.js'></script>
<script>
var arrow=[];
var colorArray=["red","orange","yellow","green","blue","navy","purple"];
var textArray=["♭","♩","♪","♬","◆","☆","★","◐","◑","○","●","◎","⊙","◈","◇","△","▲","▽","▼","□","■","◁","◀","▷","▶","◇","◆","♤","♠","♡","♥","♧","♣"];
 
 
 
//1회성이 아닌, 추후 두고두고 써먹을 코드 영역을 지정 후, 거푸집으로 선언하자
//전산에서는 이 코드 단위를 클래스라 한다
//2015년부터 ECMScript(javascript 명칭)에서는 class를 지원하기 시작했다.
//클래스명으 자가, C# 등에서 첫 철자를 대문자로 작성해야함
class Arrow{  //화살 자체가 아니라, 화살을 만들어낼 틀
    //자바스크립트에서는 사물이 보유한 변수는 constructor()라는 함수 즉 생성자 함수내에
    //작성해야하는 규칙이 있다
    constructor(y, color, velX, text){
        this.span;
        this.velX=velX; //x좌표의 속도
        this.x=0//x좌표
        this.y=y;
        this.color=color;
        this.text=text;
    }
    //사물이 보유한 함수를 가리켜, 그 사물의 동작방식, 방법을 표현한다고 하여 메서드라 한다.
    init(){
        this.span=document.createElement("span");
        this.span.style.position="absolute";
        this.span.style.left=0+"px";
        this.span.style.top=this.y+"px";
        this.span.innerText=this.text;
        this.span.style.fontSize=20+"px";
        this.span.style.color=this.color;
        document.body.appendChild(this.span);//body에 부착!!
    }   
 
    move(){
        this.x = this.x + this.velX; // x= x+10 즉 10씩 누적
        this.span.style.left=this.x+"px";
    }
}
 
function auto(){
    for(var i=0;i<arrow.length;i++){
        arrow[i].move();
    }
}
window.addEventListener("load",function(){
    //원하는만큼 거푸집으로 쇳물 붓기
    for(var i=0;i<100;i++){
        arrow[i]=new Arrow(i*10, colorArray[getRandom(colorArray.length)], getRandom(20)+1,  textArray[ getRandom(textArray.length)] ); 
        //constructor()생성자 함수의 매개변수에 y값 전달
        arrow[i].init();   
    }
 
    setInterval("auto()",100);
});
</script>
</head>
<body>
</body>
</html>
cs

 

 

script 설명

* Arrow 라는 클래스는 생성하여 constructor 생성자에 y, color, velX, text 를 매개변수로 생성한다.

* 이 매개변수를 통해 객체에 적용되는 값을 다르게 하여 객체를 생성할 수 있다.

* init() 메서드를 생성하여 그안에 <span> 태그를 생성하고 위치와 각 요소들의 속성을 지정해주고 생성자 매개변수 값에 대해서는 변수값으로 넣어준다.

* 객체 생성 후 사용할 메서드 move()를 생성한 뒤 x 값에 this.velX라는 변수를 더해주어 등속증가 식을 작성해준다.

* 그리고 x축의 값에 this.x 값을 대입하여준다.

 

* window 가 로드되었을 때 for문을 돌면서 arrow[i]번 방을 돌면서 객체를 생성해주고 각 매개변수에 대입되는 값들을 넣어주고 생성된 객체에 init() 메서드를 호출해주면 span이 body에 부착된다.

 

* auto() 함수를 생성해주고 그 안에는 for문을 돌면서 생서된 arrow배열안의 i번방 즉, 객체들에게 move() 메서드를 호출해준다.

 

* 윈도우로 돌아가서 setInterval을 auto()함수에 적용해주면 무한시 auto()가 호출되면서 모든 객체들이 move()를 무한히 반복한다.

 

 

 

 


작업 결과물 2

 

 

 

body, CSS, script 작업

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<script src="../js/Ball.js"></script>
<script src="../js/lib.js"></script>
<script>
var wrapper;
//공이 랜덤하게 나올 수 있도록, 배열로 선언해 주자
var ballArray=["ball1.png","ball2.png","ball3.png","ball4.png","ball5.png","ball6.png",
"ball7.png","ball8.png","ball9.png","ball10.png","ball11.png"];
var balls=[];//볼 여러개를 기리킬 수 있는 전역배열
 
function init(){
    createWall();
}
//공을 가두어 놓을 벽
function createWall(){
    wrapper=document.createElement("div");
    wrapper.style.width=800+"px";
    wrapper.style.height=700+"px";
    wrapper.style.margin="auto";
    wrapper.style.border=5+"px solid red";
    wrapper.style.position="relative";
    document.body.appendChild(wrapper)
}
function createBall(){
    var velX=getRandom(10)+1;
    var velY=getRandom(10)+1;
 
    //생성되는 공은 wrapper에 부착됨
    var ball=new Ball(wrapper
    , "../images/balls/"+ballArray[getRandom(ballArray.length)]
    , 3535, velX, velY); 
    balls.push(ball); //볼을 담아놓을 배열에 방금 태어난 볼을 추가
}
 
//키보드의 스페이스바를 누르면 볼을 생성해보자
function space(){
    // alert(event.keyCode);
    if(event.keyCode==32){//space bar의 아스키코드
        createBall();
    }
}
function gameLoop(){
    for(var i=0;i<balls.length;i++){
        //배열에 들어있는 공들을 하나씩 끄집어내자
        balls[i].move();
    }
}
window.addEventListener("load",function(){
    init();
    setInterval("gameLoop()",20);
});
</script>
</head>
<body onkeydown="space()">
</body>
</html>

cs

 

script 설명

* 윈도우 로드시 init()함수를 호출해준다.

* init() 함수 호출과 함께 createWall() 함수를 호출해주면서 공을 가두어 놓을 벽을 생성해준다. (createWall 함수 설명 생략)

 

* createBall()함수를 생성하고 그 안에 new Ball로 객체화를 시켜준다.

* var ball=new Ball(wrapper, "../images/balls/"+ballArray[getRandom(ballArray.length)]3535, velX, velY); 

  - 기존 Ball 클래스의 constructor(container, src, width, height, velX, velY) 양식에 맞추어 값을 대입시켜준다.

  - velX와 velY 값은 1부터 10까지 랜덤 값으로 가져온다.

  - 생성된 객체들을 balls 배열에 담는다.

 

* space() 함수안에 스페이스바를 누를때 createWall을 호출해주는 코드를 작성해주고 <body>에 onkeydown 시 space() 함수를 호출하도록 해준다.

 

* gameLoop() 라는 함수를 생성하여 호출될때마다 for문을 돌면서 balls 배열 안에 담긴 객체들이 move() 메서드를 수행하게 하고, 계속 move()를 호출해 주기 위하여 로드시 수행되는 이벤트리스너에 gameLoop() 함수를 setInterval로 무한히 호출해준다.

 

 

 

 

class 작업

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Ball{
    //new 연산자에 의해 호출되는 메서드를 생성자 메서드라 하고,
    //생성자 메서드의 목적인 이 객체가 인스턴스화 될떄, 즉 사물이
    //탄생할 떄 알맞는 개성을 부여하기 위함이다.
    //공의 모습, 상태 등 형용사 적인것, 사실은 변수값
    constructor(container, src, width, height, velX, velY){
        //객체와 함께 살아감 즉 객체가 죽을떄 같이 죽음
        //따라서 this로 명시된 객체가 보유한 변수를 가리켜 멤버변수라고 한다.
        this.container=container;//어디에 붙일이 결정짓지 말고, 호출자가 결정
        this.src=src;
        this.x=0;
        this.y=0;
        this.width=width;
        this.height=height;
        this.velX=velX; //좌우를 결정하는 변수 +일때 증가, -일떄는 감소
        this.velY=velY; //상하를 결정하는 변수
        this.limitX=parseInt(this.container.style.width); //공의 x축 한계점
        this.limitY=parseInt(this.container.style.height); //공의 y축 한계점
        this.r=0//각도
        
        this.img=document.createElement("img"); //공을 감쌀 img
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
        // this.img.style.background="red";
        this.img.src=this.src;
        this.img.style.position="absolute";
        this.img.style.left=0+"px";
        this.img.style.top=0+"px";
        
        //img를 부모요소에 부착
        this.container.appendChild(this.img)
 
    }
    
    move(){
        this.x+=this.velX; //10씩 증가하는 등속도 운동
        this.y+=this.velY; //10씩 증가하는 등속도 운동2
 
        //축의 경계에 다다르면
        if(this.y>=this.limitY-this.height || this.y<=0){
            this.velY*=-1;   
        }
        if(this.x>=this.limitX-this.width || this.x<=0){
            this.velX*=-1;
        }
 
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
        this.r++;
        this.img.style.transform="rotate("+this.r+"deg)";
    }
}
cs

 

class 설명

* Ball을 여러개 생성할 예정임으로 틀인 Ball 클래스를 만들어준다.

* 생성자 메서드 constructor()에 멤버 변수를 선언해주고 공의 위치, 이미지경로 등을 정의해준다.

* (container, src, width, height, velX, velY) 생성자에 매개변수를 선언해주어 객체화시 매개값을 받아올수 있게 한다.

 

* 객체화 한 뒤 호출할 move() 메서드를 생성한다.

* x, y 값이 velX,Y 만큼씩 등속으로 증가하는 식을 적어준다.

* 만약에 <div>의 축 경계에서 이미지 너비와 높이만큼을 빼준 위치에 도착하면 증가하는 값을 *-1을 곱해서 증가하던 공을 감소시키거나 감소하던 공의 위치를 증가시켜서 <div> 이상으로 벗어나지 못하게 한다.

* 변수 r값을 주어 move() 메서드가 호출될때마다 this.r 값을 1도씩 회전시켜준다.

 

 

 

lib.js 라이브러리

 

1
2
3
4
5
6
7
/* -----------------------------------------------------
매개변수 n : 0~n미만까지의 랜덤한 수를 반환하는 함수
------------------------------------------------------*/
function getRandom(n){
    var r=parseInt(Math.random()*n); //0.00xxx ~ 1미만 사이의 난수를 발생시켜줌 
    // console.log(r);
    return r;
cs

 

* 재사용할수 있게 따로 라이브러리를 생성하여 lib.js를 <script>로 불러오면 사용이 가능하다.

 

 


작업 결과물 3

 

 

 

 

body, CSS, script 작업

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <tite></title>
    <script src="../js/Bar.js"></script>
    <script src="../js/lib.js"></script>
    <script>
var wrapper;
var barArray=new Array(); //막대기 1개를 담는 전역배열
var colorArray=["red","orange","yellow","green","blue","navy","purple"];
var count=0//수를 세기 위한 카운터 변수
var flag=true;
 
function init(){
    wrapper=document.getElementById("wrapper");
    wrapper.style.width=500+"px";
    wrapper.style.height=400+"px";
    wrapper.style.margin="auto";
    wrapper.style.border="4px solid blue";
    wrapper.style.position="relative";
 
    createBar();
}
function createBar(){
    //생성자의 프로토타입 (container, width, height, x, y, bg, targetH)
    for(var i=0;i<10;i++){
        bar=new Bar(wrapper, 501050*i, 0, colorArray[getRandom(colorArray.length)], getRandom(350)+10);
        //생성된 막대기 1개를 배열에 넣자
        barArray.push(bar); //생성된 막대기 1개를 배열에 넣자
    }
}
//게임에서 움직이는 모든 호출은 여기서 진행! 게임루프(게임의 심장)
function gameLoop(){
    if(flag){
        for(var i=0;i<barArray.length;i++){//생성된 바 갯수만큼
            barArray[i].render();
        }
        count++;
        setTarget();
    }
}
//일정 시간 간격으로, 어떤 바를 움직일지 를 결정하여, 그 bar를 targetH 값을 지정해보자
function setTarget(){
    // console.log("setTarget()호출함", count);
    //늦출 필요가 있을때는 조건을 줘야한다.
    if(count%3==0){
        barArray[getRandom(barArray.length)].targetH=getRandom(350)+10;
    }
}
 
window.addEventListener("load",function(){
    init();
    setInterval("gameLoop()",10); //fps-frame per seconds
});
</script>
</head>
<body>
   <div id="wrapper"></div>
   <!-- 자바스크립트 작성할 수 있는 영역
    1) script 태그안
    2) 이벤트 핸들러 안
    3) a href="javascript:영역" -->
   <button onclick="flag=!flag">on/off</button>
</body>
</html>
cs

 

script 설명

* 윈도우가 로드되었을 때  init()을 호출한다.

* init() 함수에 wrapper 영역의 <div>를 동적으로 style을 지정해 주고 createBar() 함수를 호출해 준다.

 

* createBar() 함수가 호출될 때마다 for문을 돌면서 new Bar로 객체화 시켜준다.

* bar=new Bar(wrapper, 501050*i, 0, colorArray[getRandom(colorArray.length)], getRandom(350)+10);

  - 기존 Bar 클래스의 (container, width, height, x, y, bg, targetH) 양식에 맞추어 값을 넣어준다.

  - 생성된 bar객체를 barArray 배열에 넣어준다.

 

* gameLoop()에서는 게임에서 움직이는 모든호출을 넣어주는데 만약 flag가 true라면 for문을 돌면서 barArray 배열에 들어있는 객체들에게 render() 메서드를 호출시켜준다. 

* 그리고 count를 증가시켜주면서 setTarget() 함수를 호출시켜준다.

 

* setTarget() 함수는 count가 3의 배수 일때 barArray안의 객체들을 랜덤으로 선정해주어 그 targetH 값을 랜덤으로 선정해준다. 이렇게 되면 10/1000초가 3번 돌았을때 랜덤으로 선정된 객체의 targetH 값이 변경되면서 연속적이 아닌 조금 지연되어 bar의 높이가 변경 될 수 있다. 

 

 

class 작업

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 현실의 객체 중 이퀄라이저는 막대기
// 우리가 정의한 객체를 가리켜 사용자 정의객체라 한다.
// Bar객체 자료형을 개발자가 정의했다는 것은 기존에 없던 새로운 자료형을
// 정의했다고 하여, Bar형이라고 한다. 즉 개발자가 창조주가 되는것
 
class Bar{
    /*클래스란 기존의 고전적인 절차지향 언어에서 사용하던 재료들
    즉 변수와 함수를 묶어 하나의 단위로 정의한 것에 불과하므로,
    신기술이라기 보다는, 현실을 반영하는 개발자의 관점이 변화된것이다 */
    constructor(container, width, height, x, y, bg, targetH){
        /*매서드 중 객체의 인스턴스 생성시점에 관여하여
        객체의 개성을 부여할 수 있도록, 즉 초기화 할 수 있도록 역할을
        수행하는 메서드를 특별히 생성자 매서드라 한다
        개발자는 여기서 이 사물이 태어날때 어떠한 개성을 가지고 태어날지
        즉 스타일을 결정할 수 있다. "객체의 초기화" */
        this.container=container;
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
        this.bg=bg;
        this.a=0.1//비율계수
        this.targetH=targetH;
 
        this.div=document.createElement("div");
        //크기
        this.div.style.width=this.width+"px";
        this.div.style.height=this.height+"px";
        //위치
        this.div.style.position="absolute";
        this.div.style.left=this.x+"px";
        this.div.style.top=this.y+"px";
        //배경
        this.div.style.background=this.bg;
        //부모 요소에 부착
        this.container.appendChild(this.div);
        //테두리
        this.div.style.border="1px solid black";
        // box 모델 크기에 영향주지 않기
        this.div.style.boxSizing="border-box";
 
    }
 
    //객체가 보유한 변수들을 이용하여 원하는 변화를 주면, 움직임을 표현할 수 있다
    //즉 움직임 방식을 결정할 수 있는 객체안의 함수를 가리켜 메서드(method)
    render(){//화면에 보여질 철=게임분야에서 렌더링;
        // 물체의 위치=기존물체위치+비율*(목표지점-물체기존위치))
        this.div.style.height=parseFloat(this.div.style.height)
        +this.a*(this.targetH-parseFloat(this.div.style.height))
        +"px";
        this.div.innerText=this.div.style.height;
 
    }
}
cs

 

class 설명

* 여러 Bar를 생성할 예정이기 때문에 class Bar를 생성하여 준다.

* 생성자 메서드를 선언하고 매개변수로 (container, width, height, x, y, bg, targetH)를 가져오고 각 변수들에 대하여 멤버변수로 선언해준다.

* bar의 크기, 위치, 색상등을 멤버변수의 this.~~ 값으로 넣어준다.

 

* render() 메서드는 게임에 보여질 부분을 코드로 구현한다.

* 생성될 bar <div>의 높이는 물리식에 의해 targetH에 한없이 가까워진다.

* <div> 텍스트는 각 <div>의 높이가 표현이 된다.

 

 

 

 

반응형

'개발 > HTML&JS' 카테고리의 다른 글

htm 슈팅게임  (0) 2021.03.25
html 충돌검사  (0) 2021.03.24
html 다차원 배열2  (0) 2021.03.18
html 다차원 배열1  (0) 2021.03.17
html 1차원 배열2  (0) 2021.03.17

댓글