코딩/1-JavaScript

_05_버튼이미지 ~ _09_삼각함수 ( 4 ~ 7 )

tree0505 2025. 6. 11. 16:18
반응형
  • _06_사각형벽충돌

  • rectDir.html
  • <!DOCTYPE html>
    <html lang="ko">
    <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>
    </head>
    <body>
        <canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;">
        </canvas>
        <div class="testText"></div>
        <script src="rectDir.js"></script>
    </body>
    </html>

  • rectDir.js
    // draw() 함수 내부에서:
    // 캔버스를 지우고
    // 사각형을 그리고
    // 위치를 업데이트하며
    // 방향을 체크하는 모든 동작이 실행됩니다.

    function draw() {
        // 캔버스를 지운다.
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 캔버스를 다시 그린다.
        drawRect();
        //사각형을 그리는 함수입니다.
        // drawRect()는 따로 정의되어 있고,
        // 이 함수 안에서 ctx.rect()와 ctx.fill()을 통해 파란 사각형을 캔버스에 그립니다.

        //이동제어
        if(dir == "east"){
            x += speed ; //이것때문에 움직이는건가?>
            //방향이 east면 속도를 x를 증가시키고
            //
        }else if(dir == "west"){
            x -= speed;
            //west이면 x를 감소시킨다.
        }

        //충돌제어
        if(x >= canvas.width - width){
            //내가 붇딛히면
            // canvas.width의 가로에 x가 붇힣히면
            //width 이걸 왜 빼주냐. 빼주지 않으면. 사각형이 나가니까. 나가기 전에 방향전환하기 위해
            dir ="west";
        }
        else if(x < 0){
            dir ="east";
        }

        let testText = document.querySelector(".testText");
        testText.innerHTML = ``;
        testText.innerHTML += `x  : ${x} <br>`;
        testText.innerHTML += `y  : ${y} <br>`;
        testText.innerHTML += `dir  : ${dir} <br>`;
        testText.innerHTML += `speed : ${speed} <br>`;
    }


    //함수는 캔버스에 파란색 사각형을 그리는 역할
    function drawRect(){
        ctx.beginPath();

        ctx.rect(x, y, width, height); //여기서 x를 넣어서
        //여기 x가 계속 봐뀌는거다.
        ctx.fillStyle = "blue";
        ctx.fill();

        ctx.closePath();
    }

    //-------------------------------------------------
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");

    let x = 0; //사각형의 x 좌표
    //변수가 밖에 있으니까. x가 계속 증가한다.
    //이 변수가 계속 바뀌는거다.
    //변수가 x가 계속 늘어나서. 이동이 된다.

    let y = 0;
    let dir = "east"; //방향이 있다.  //사각형의 이동 방향을 나타냅니다.
    let width = 100; //사각형의 가로 크기입니다.
    let height = 100;
    let speed = 2; //속도

    setInterval(draw, 10);
    //draw();
        //딱 한 번만 실행됩니다.
        // 그래서 사각형은 움직이지 않고, 한 번 그려진 후 멈춰 있는 거예요.

  • 변수를 계속 바꾸고 싶다면. 반복문 밖에서 변수를 적어야. 변수의 값이 변한다. 
  • 만약 반복문 안에 변수를 적으면. 변수의 값이 안 바뀌고. 반복문이 끝나면 변수는 사라진다.
    <script>
        let x = 10;
        for(let i = 0; i < 4; i++){
            x += 1;
        }
        document.writeln(x);

        //-------------------
        //변수를 계속 바뀌게 하고 싶으면
        //for 반복문 밖에 두어야지. 변수 x의 값이 바뀐다.
    //-----------------------------------------
     
        for(let i = 0; i < 4; i++){
            let x1 = 10; //안 바뀐다.
            // 중괄호 때문에.
            // 밖에서 출력을 하면 에러난다. 변수가 사라져서.
            // 변수는 사라졌다가 생긴다가.
            // 4번 반복하고 사라진다.  
            x += 1;
        }
        document.writeln(x);    
        //만약 변수를 바꾸고 싶지 않으면
        //for안에 넣어야 한다.
        //for안에

    </script>

 

<script>
 
//두 코드 블록의 가장 큰 차이는 **변수의 "유효 범위(scope)"*


  //--------------------------
   let x = 10;  //x는 for문 바깥에서 선언됨 → 전역(또는 상위 스코프) 변수.
   for(let i = 0; i<4; i++){
        x += 1;
        //for문 안에서 x += 1 → 값을 4번 증가.
   }
   document.writeln(x);
   //14출력
   //x는 여전히 유효하기 때문에 바깥에서도 출력 가능.
   // 즉, 변수 x는 for문 바깥에서도 계속 살아있음.
   document.writeln("<br>");

   //--------------------------

   for(let i = 0; i<4; i++){
        let x1 = 10;
        //x1은 for문 안의 블록 {} 안에서 선언됨 (let x1 = 10)
        // 그래서 반복할 때마다 새롭게 생성되고, 반복문 밖에서는 완전히 사라짐.
        x1 += 1;
        document.writeln(x1);
        // 11 11 11 11 출력됨
   }
   document.writeln(x1);
   //오류 발생: x1 is not defined
   // 이건 출력이 안된다.
   //  let x1 = 10;  => 이건 중괄호에서 사라진다.
</script>

  • _07_사각형리스트

  • rectList.html
  • <!DOCTYPE html>
    <html lang="ko">
    <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>
    </head>
    <body>
        <h1>사각형을 클릭하세요.</h1>
        <canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;">
        </canvas>
        <div class="testText"></div>
        <script src="rectList.js"></script>
    </body>
    </html>

  • rectList.js
    function draw() {
        // 캔버스를 지운다.
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 캔버스를 다시 그린다.
        // //캔버스를 그냥 for문으로 돌린것
        // 그냥 함수 실행
        for(let i = 0; i < rectList.length; i++){
           
            drawRect(rectList[i]);
            //현재 인덱스 i에 해당하는 사각형 객체를 drawRect() 함수에 전달합니다.
            // 이 함수는 전달받은 객체의 정보(x, y, width, height, color)를 이용해 사각형을 캔버스에 그림니다.
            drawText(rectList[i]);
            //같은 객체를 drawText() 함수에 전달합니다.
            // 이 함수는 number 값을 꺼내서 사각형 안에 텍스트를 출력합니다.
        }  
    }
    //-------------------------------------------------
    //그린것
    function drawRect(node){ //node???
       
        //rectList[i] => 객체가 배열안에 들어갔으니까. 객체의 정보를 알 수 있고.
         //drawRect(rectList[i]);  ==  drawRect(node)
            //그냥 이름을 바꾼것


        ctx.beginPath();
        ctx.rect(node.x, node.y, node.width, node.height);
        // (rectList[i]); => i때문에 다르게 그려지는거다.
        ctx.fillStyle = node.color;
        ctx.fill();
        ctx.closePath();

        //이 함수는 한번 그리는 용도. 4번이 그려지는 이유는  for(let i = 0; i < rectList.length; i++){ 때문이다.
    }
    //-------------------------------------------------
    //글자 바꿔준것
    function drawText(node){
        ctx.font ="25px Fira";
        ctx.fillStyle = "white";
        ctx.fillText(node.number, node.x + 8, node.y + 28);
    }
    //-------------------------------------------------
    //여기는 밑에 있는 변수값들을 바꾸나?
    window.addEventListener('click', (event) => {
       
        let mx = event.clientX - ctx.canvas.offsetLeft;
        let my = event.clientY - ctx.canvas.offsetTop;

        let testText = document.querySelector(".testText");
        testText.innerHTML = ``;
        testText.innerHTML += `mx  : ${my} <br>`;
        testText.innerHTML += `my : ${my} <br>`;

        //for문 돌려서 사각형 위치 찾아서
        for(let i = 0; i < rectList.length; i++){
            let x = rectList[i].x;
            let y = rectList[i].y;
            let width = rectList[i].width;
            let height = rectList[i].height;

            //사각형 위치 찾는다.
            if(x < mx && mx < x + width && y < my && my < y + height){
                rectList[i].number = gameNumber;
                gameNumber += 1;      
            }

            // 출력
            testText.innerHTML += `x : ${x} y : ${y} width : ${width} height : ${height}<br>`;
        }
    });

    //-------------------------------------------------
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");

    let originx = 100;
    let originy = 100;
    //첫 번째 사각형이 시작할 x, y 좌표 (기준점)

    let gap = 50; //사각형 사이 간격
    let width = 50;
    let height = 50;
    //모든 사각형의 크기 (가로, 세로)

    let rectList = []; //사각형들을 저장할 배열 생성
    // for 반복문은 사각형 4개를 만들어서 rectList 배열에 저장하는 코드
    //사각형 4개를 만들기 위한 준비 작업"**이라고 보면 돼요.
    for(let i = 0; i < 4; i++){
        //각각의 i는 1개의 사각형을 만들기 위한 인덱스입니다.
        let startx = originx + i * width + i * gap;
        //사각형의 x 위치를 계산합니다.
        // originx는 기준점이고, i에 따라 사각형들이 오른쪽으로 나란히 그려집니다.
        let starty = originy; //y는 모두 같은 값 (originy)으로 지정되어 가로로 한 줄에 나열됩니다.
       
        let myRect = {
            "x" : startx,
            "y" : starty,
            "width" : width,
            "height" : height,
            "number" : 0,
            "color" : "blue",
        };
        rectList.push(myRect);
        //만든 사각형을 rectList라는 배열에 추가(push) 합니다.
        // 결과적으로 rectList에는 4개의 사각형 정보가 순서대로 들어가게 됩니다.
    }
    let gameNumber = 1;

    setInterval(draw, 10);




 


  • _08_사각형클릭이동

  • rectListMove.html
  • <!DOCTYPE html>
    <html lang="ko">
    <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>
    </head>
    <body>
        <h1>사각형을 클릭하세요.</h1>
        <canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;"></canvas>
        <div class="testText"></div>
        <script src="rectListMove.js"></script>
    </body>
    </html>

  • rectListMove.js
  • function draw() {
        // 캔버스를 지운다.
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 캔버스를 다시 그린다.
        for(let i = 0; i < rectList.length; i++){
            drawRect(rectList[i]);
        }    
       
        for(let i = 0; i < rectList.length; i++){
            if(rectList[i].check == true){
                rectList[i].y += rectList[i].speed;

                if(rectList[i].y + rectList[i].height > canvas.height){
                    //바닥까지 가면
                    rectList[i].y = originy;
                    rectList[i].check = false; //false가 된다.
                    rectList[i].color = "blue";
                    //파란색이 되서. 다시 클릭할 수 있게 된다.
                }
            }
        }

        let testText = document.querySelector(".testText");
        testText.innerHTML = ``;
        for(let i = 0; i < rectList.length; i++){
            testText.innerHTML += `x : ${rectList[i].x} y : ${rectList[i].y} width : ${rectList[i].width} height : ${rectList[i].height} <br>`;
            testText.innerHTML += `check : ${rectList[i].check}  <br>`;
        }

    }

    function drawRect(node){
        ctx.beginPath();
        ctx.rect(node.x, node.y, node.width, node.height);
        ctx.fillStyle = node.color;
        ctx.fill();
        ctx.closePath();
    }


    window.addEventListener('click', (event) => {

        let mx = event.clientX - ctx.canvas.offsetLeft;
        let my = event.clientY - ctx.canvas.offsetTop;

        for(let i = 0; i < rectList.length; i++){
            let x = rectList[i].x;
            let y = rectList[i].y;
            let width = rectList[i].width;
            let height = rectList[i].height;
            let check = rectList[i].check;
            if(check == false){
                //체크가 false면 클릭할 수 있게.
                if(x < mx && mx < x + width && y < my && my < y + height){
                    rectList[i].check = true; //true로 바뀌어서 안눌린다.
                    rectList[i].color = "red";
                }
            }
           
        }
    });
    //-------------------------------------------------
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");

    let originx = 100;
    let originy = 100;
    let gap = 50;
    let width = 50;
    let height = 50;

    let rectList = [];

    for(let i = 0; i < 4; i++){

        let startx = originx + i * width + i * gap;
        let starty = originy;
       
        let myRect = {
            "x" : startx,
            "y" : starty,
            "width" : width,
            "height" : height,
            "color" : "blue",
            "speed" : 2,
            "check" : false, //체크값을 더 줬다.
        };
        rectList.push(myRect);
    }

    setInterval(draw, 10);




  • _09_삼각함수

  • 면접문제에 나왔다. 아날로그 시계를 만드시오 

  • 삼각함수가 뭐냐? 
  • 삼각형을 그리고 싶다. 
  • 삼각형을 그릴릴려면 
    • 3선의 길이
    • 3 각 
    • 3 꼭짓점을 알아야 한다. 
  • 사실은 위의 3개의 정보를 다 없어도 삼각형을 그릴 수 있다. => 이게 삼각함수이다. 

  • 일부의 정보를 가지고 삼각형을 그릴 수 있다. => 삼각함수 

  • 수학의 핵심이다.
    • 일부의 정보를 가지고 전체를 알아내는것 

  • 아날로그 시계에서 우리에게 주워진것 
    • 작대기 선과. 각도를 주워진다. 
    • let len = 200;
      let angle = 3.14;
    • 선 한개와. 그 사이값만 주워짐 


  • 삼각형을 구할때.
    • 한변의 길이를 알고 있다고 하면. 
    • 한변의 길이가 5 * 0. ~~~ 하면 
    • 나머지 한변의 길이를 알 수 있따. 
  • 그럼 0. ~~ 의 숫자를 어떻게 구하냐. 
  • 삼각비 표를 치면 나온다. 

  • 각도 * 코사인 * 5 하면 밑에 길이가 나온다. 
  • 세로는 사인을 곱하면 된다. 

  • 이걸 구해주는 함수가 
  •  let cosAngle = Math.cos(angle); 
        // cos => 코싸인 값을 알려주는 함수 
        let sinAngle = Math.sin(angle);
        //sin => 사인 값을 알려주는 함수 

  • 코사인 => 각도를 소수점으로 바꿔주는 함수
  • 소수점에다가 대각형길이를 곱하면 가로를 구해준다. 

_09_삼각함수


  • triangle.html
  • <!DOCTYPE html>
    <html lang="ko">
    <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>
    </head>
    <body>
        <canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;">
        </canvas>
        <div class="testText"></div>
        <script src="triangle.js"></script>
    </body>
    </html>

  • triangle.js
  • function draw() {
        // 캔버스를 지운다.
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.beginPath();

        // 코사인법칙 2변과 사잇각을 알고있을때, 세변과 그 각을 알수있다.

        //코사인 => 각도를 소수점으로 바꿔주는 함수 이다.
        //소수점에다가 대각형길이를 곱하면 가로를 구해준다.

        let cosAngle = Math.cos(angle);
        // cos => 코싸인 값을 알려주는 함수
        let sinAngle = Math.sin(angle);
        //sin => 사인 값을 알려주는 함수


        let endX = x + len * cosAngle;
        let endY = y + len * sinAngle;

        ctx.moveTo(x, y);
        ctx.lineTo(endX, endY);  
        ctx.stroke();        
       
        angle += 0.01;
        angle %= 6.28; //0으로 돌려놓음. 넘으면 안되서

        ctx.closePath();

        let testText = document.querySelector(".testText");
        testText.innerHTML = ``;
        testText.innerHTML += `x  : ${x} <br>`;
        testText.innerHTML += `y  : ${y} <br>`;
        testText.innerHTML += `angle  : ${angle} <br>`;
    }

    //-------------------------------------------------
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");

    let x = 300;
    let y = 300;
    let len = 200;
    let angle = 3.14;

    setInterval(draw, 10);

 

반응형