JavaScript 기초-06

wonder1ng·2026년 5월 7일

풀스택 기초

목록 보기
10/13

14 Canvas

JavaScript와 HTML <canvas> 엘리먼트를 통해 그래픽을 그리기위한 수단을 제공하며 주로 애니메이션, 게임 그래픽, 데이터 시각화, 사진 조작 및 실시간 비디오 처리를 위해 사용됨. 출처: MDN Canvas Api

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        height: 150px;
      }
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <!-- mdm의 canvas 튜토리얼과 ChatGPT로 학습함 -->
    <!-- https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/ -->
    <!-- canvas는 내부 HTML 렌더링 안 해서 아래 내용들은 안 보임 -->
    <canvas id="tuto" width="150" height="150">
      current stock price: $3.15 +0.15
    </canvas>
    <canvas id="cat1" width="150" height="150">
      <img
        src="https://images.pexels.com/photos/35575789/pexels-photo-35575789/free-photo-of-charming-fluffy-cat-posing-outdoors-on-a-wall.jpeg"
        width="150"
        height="150"
        alt=""
      />
    </canvas>

    <!-- canvas 요소는 영역 생성을 담당하고 js로 랜더링 해서 보여줌 -->
    <canvas id="cat2" width="150" height="150"></canvas>
    <script>
      const canvasTuto = document.getElementById("tuto");
      if (canvasTuto.getContext) {
        var ctxTuto = canvasTuto.getContext("2d");
        draw();
      } else
        // 익스플로러는 9버전부터 지원이니 현재는 전부 지원한다 보면 됨
        alert(
          "canvas를 지원하지 않는 브라우저입니다. 최신 브라우저를 이용해주세요.",
        );
      function draw() {
        ctxTuto.fillStyle = "#c80000";
        ctxTuto.fillRect(10, 10, 50, 50);
        ctxTuto.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctxTuto.fillRect(30, 30, 50, 50);
      }

      const canvas = document.getElementById("cat2");
      // rendering contexts
      const ctx = canvas.getContext("2d");

      const img = new Image();
      img.src =
        "https://images.pexels.com/photos/35575789/pexels-photo-35575789/free-photo-of-charming-fluffy-cat-posing-outdoors-on-a-wall.jpeg";

      img.onload = function () {
        ctx.drawImage(img, 0, 0, 150, 150);
      };
    </script>
  </body>
</html>

canvas는 위의 코드처럼 canvas 요소를 통해 js로 내용을 채움

14-01 stroke and diagram

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="300" height="300"></canvas>
    <canvas id="canvas2" width="300" height="300"></canvas>
    <script>
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");

      // rectangle
      // x시작점, y시작점, 가로 이동, 세로 이동
      ctx.fillRect(25, 25, 100, 100);
      ctx.clearRect(45, 45, 60, 60);
      ctx.strokeRect(50, 50, 50, 50);

      // stroke and triangle
      ctx.beginPath();
      ctx.moveTo(175, 50); // 좌표만 지정하고 그리진 않음
      ctx.lineTo(200, 75); // 해당 좌표까지 움직이며 그림
      ctx.lineTo(200, 25);
      ctx.fill(); // 해당 범위를 칠함

      // arc(circle)
      ctx.fillStyle = "#FFFF00";
      ctx.beginPath();
      ctx.arc(250, 50, 30, 0, 2 * Math.PI); // x, y, 반지름(radius), 출발각도, 끝각도(360)
      // 각도는 radian 기준으로 입력하며 0은 3시에서 시작하여 시계 방향으로 이동하며 2π가 360도(degree)
      ctx.fill();
      ctx.closePath();

      ctx.fillStyle = "#000";
      ctx.beginPath();
      ctx.arc(250, 150, 30, 0, 5, false); // x, y, 반지름(radius), 출발각도, 끝각도(360), 반시계방향(true, false)
      ctx.fill();
      ctx.closePath();

      ctx.fillStyle = "#00FFFF";
      ctx.beginPath();
      ctx.arc(250, 250, 30, (Math.PI * 1) / 2, (3 / 2) * Math.PI); // x, y, 반지름(radius), 출발각도, 끝각도(360)
      ctx.fill();
      ctx.closePath();

      ctx.beginPath();
      ctx.arc(75, 175, 50, 0, Math.PI * 2, true); // Outer circle
      ctx.moveTo(110, 175);
      ctx.arc(75, 175, 35, 0, Math.PI, false); // Mouth (clockwise)
      ctx.moveTo(65, 165);
      ctx.arc(60, 165, 5, 0, Math.PI * 2, true); // Left eye
      ctx.moveTo(95, 165);
      ctx.arc(90, 165, 5, 0, Math.PI * 2, true); // Right eye
      ctx.stroke(); // 칠하지 않고 라인만 그림

      // 이차 베지에 곡선(Quadratic Bezier curves)
      const canvas2 = document.getElementById("canvas2");
      const ctx2 = canvas2.getContext("2d");
      // Quadratric curves example
      ctx2.beginPath();
      ctx2.moveTo(225, 25);
      // cpx(ChangePointX), cpy(ChangePointY), x, y): cpx, cpy를 지나가는 게 아니라 그 쪽으로 휘는 것
      ctx2.quadraticCurveTo(175, 25, 175, 62.5);
      ctx2.quadraticCurveTo(175, 100, 200, 100);
      ctx2.quadraticCurveTo(200, 120, 180, 125);
      ctx2.quadraticCurveTo(210, 120, 215, 100);
      ctx2.quadraticCurveTo(275, 100, 275, 62.5);
      ctx2.quadraticCurveTo(275, 25, 225, 25);
      ctx2.stroke();

      // Cubic curves example
      ctx2.beginPath();
      ctx2.moveTo(75, 40);
      // cp1x, cp1y, cp2x, cp2y, x, y
      ctx2.bezierCurveTo(75, 37, 70, 25, 50, 25);
      ctx2.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
      ctx2.bezierCurveTo(20, 80, 40, 102, 75, 120);
      ctx2.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
      ctx2.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
      ctx2.bezierCurveTo(85, 25, 75, 37, 75, 40);
      ctx2.fill();

      // path2D: 도형(그림)을 객체로 생성
      var rectangle = new Path2D();
      rectangle.rect(10, 210, 50, 50);

      var circle = new Path2D();
      circle.arc(100, 235, 25, 0, 2 * Math.PI);

      ctx2.stroke(rectangle);
      ctx2.fill(circle);

      // svg로 그리기
      // M ? ?(시작 좌표), v ?(가로 이동), h ?(세로 이동), Z 닫기(시작점으로 자동 연결)
      // 대문자: 절대좌표, 소문자: 상대좌표
      var p = new Path2D("M150 200 h120 v 30 h -50 Z");
      ctx2.stroke(p);
    </script>
  </body>
</html>
  • 코드 결과

14-02 style

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Demo</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="700" height="600"></canvas>
    <br />
    Change the <code>miterLimit</code> by entering a new value below and
    clicking the redraw button.<br /><br />
    <form onsubmit="return drawMiterLimit();">
      <label>Miter limit</label>
      <input type="text" size="3" id="miterLimit" />
      <input type="submit" value="Redraw" />
    </form>
    <script>
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");

      // =============================
      // 1. 색상 박스
      // =============================
      for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
          ctx.fillStyle = `rgb(${Math.floor(255 - 42.5 * i)}, ${Math.floor(255 - 42.5 * j)}, 0)`;
          ctx.fillRect(j * 25, i * 25, 25, 25);
        }
      }

      // =============================
      // 2. 원 (stroke 색 변화)
      // =============================
      for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
          ctx.strokeStyle = `rgb(0, ${Math.floor(255 - 42.5 * i)}, ${Math.floor(255 - 42.5 * j)})`;
          ctx.beginPath();
          ctx.arc(j * 25 + 162.5, i * 25 + 12.5, 10, 0, Math.PI * 2);
          ctx.stroke();
        }
      }

      // =============================
      // 3. globalAlpha
      // =============================
      ctx.fillStyle = "#FD0";
      ctx.fillRect(300, 0, 75, 75);
      ctx.fillStyle = "#6C0";
      ctx.fillRect(375, 0, 75, 75);
      ctx.fillStyle = "#09F";
      ctx.fillRect(300, 75, 75, 75);
      ctx.fillStyle = "#F30";
      ctx.fillRect(375, 75, 75, 75);

      ctx.fillStyle = "#FFF";
      // globalAlpha: 값 할당 후부터 생성 개체 적용
      ctx.globalAlpha = 0.2;

      for (let i = 0; i < 7; i++) {
        ctx.beginPath();
        ctx.arc(375, 75, 10 + 10 * i, 0, Math.PI * 2);
        ctx.fill();
      }

      ctx.globalAlpha = 1;

      // =============================
      // 4. lineWidth, lineCap + lineJoin
      // =============================

      // lineCap: 선 끝처리, butt: 기본값, round: 둥글게, square: 네모나게 튀어나옴
      const lineCap = ["butt", "round", "square"];
      // lineJoin: 선끼리 만나는 모서리 처리, miter: 기본값으로 모서리 뾰족하게, round: 모서리 둥글게, bevel: 모서리 비스듬한 삼각형
      const lineJoin = ["miter", "round", "bevel"];

      for (let i = 0; i < 10; i++) {
        // lineWidth: 선 굵기
        ctx.lineWidth = i;
        ctx.lineCap = lineCap[i % lineCap.length];
        ctx.lineJoin = lineJoin[i % lineJoin.length];

        ctx.beginPath();
        ctx.moveTo(i * 45, 160);
        ctx.lineTo(i * 45, 290);
        ctx.lineTo(i * 45 + 20, 290);
        ctx.stroke();
      }

      // lineCap 비교용 기준선
      ctx.lineWidth = 1;
      ctx.strokeStyle = "#09f";
      ctx.beginPath();
      ctx.moveTo(10, 160);
      ctx.lineTo(450, 160);
      ctx.stroke();
      ctx.strokeStyle = "#000";

      // =============================
      // 5. setLineDash 비교
      // =============================
      // dashPatterns[nOdd, nEven, ...]: 대시 길이 패턴 지정, nOdd: 대시 길이, nEven: 쉬는 길이
      const dashPatterns = [
        [10, 5],
        [5, 5],
        [20, 10, 5, 5],
        [2, 4],
        [4, 2],
      ];

      ctx.lineWidth = 3;
      console.log("dash");
      for (let i = 0; i < dashPatterns.length; i++) {
        ctx.setLineDash(dashPatterns[i]);
        // getLineDash: 대시 패턴값 반환
        console.log(`${i}번 대시 패턴: ${ctx.getLineDash()}`);
        ctx.beginPath();
        ctx.moveTo(20, 320 + i * 20);
        ctx.lineTo(300, 320 + i * 20);
        ctx.stroke();
      }

      // =============================
      // 6. lineDashOffset 비교
      // =============================
      ctx.setLineDash([10, 5]);
      // lineDashOffset: 선 안에서 대시의 시작 위치 지정.
      for (let i = 0; i < 6; i++) {
        ctx.lineDashOffset = i * 10;

        ctx.beginPath();
        ctx.moveTo(350, 320 + i * 20);
        ctx.lineTo(650, 320 + i * 20);
        ctx.stroke();
      }
      ctx.setLineDash([]);

      // =============================
      // 7. miterLimit 비교
      // =============================
      // 아래 링크 참고
      // https://developer.mozilla.org/ko/play?uuid=89a0aeb83ed49f61a185f0c9d58cb91078df98cc&state=lVTfq9xEFP5XPkaExLvdZFdX8SbZgkVBsCC16Mu8TJKzm7GTyZJMdu9aLpS6gtQ38b6Ilftw65MPpRT8Qf%2Bibvo%2FyCQ3d9NiC32ZOTNzznd%2BfOfMXZaZXLFjFhoRK5pzDYSmbHcrpfMwEXotKsg04qyTOcNGpiaLOJvMfM6QkVxmpj%2FOQ6%2FTm4eeSQdQnQTcyIReEkxGCJMipXkuDZVfyFya0GsvEG9B2lAp9RICmjZYC1UTYlLFBkKnPVaiZHLHalm0ktJSbBDXxhR6HMYlvHm39urhoihzFLqq41zaiEsydalh7Rw34OxKEwiViEnNb9rgoLrouquBjtSr2sBsVxRxZujEcIZKfmdP73PWVe2QHmeDWF617mLirEs14uxWm85LNqFnE%2Bhr2pc39FrKQq8nkY1YUlXsmLER%2B9bui1onRhZ9orhrzdaiRGJOECEtkjonbcZLMp8qsuIn289T58C4a59uFNqm6HA2TTlzA64tjOeh%2BfeX%2FZNd8%2BBi%2F%2BgZ9v%2Fsml%2Bf7n%2B6sI%2BJORknikR5ixLj%2BCP4I0xm3TIEOPtxf%2F9psztvHu7w%2FK%2B%2F9388HgBUpizu0FdmqwgROHvH%2F3jBWdA%2FK6npG9uQiDANXjZq3V6bjdD6%2FNC3wtDv7hzNg4sX399rHj6zvpvdRXN%2B9uLstze69%2F3XuJ%2F4A%2Bzff9ifP8Lzxz%2B3ST2519z%2F8wAsF3BeX%2FZhy7jjtiHGuTBJ5nicp0cO52O7u9c995LMLpaDHSKsRFnRZ6oQ5u08uW1qpyBVUQ8uFJWW%2BK%2FbMczryiAmCKyKShq5Jug6j6nsugI4HVb4fzmNaSn1l8JkjntVybxY0%2B3CdsnE97vrRVHCkYjgB5AIMf0ggDw6ukra9nC6RQSJdzFFFMHHdUxnOMa16Sw4VMaydLtwbgqTjVfFxpEjTMYzF%2B9hOsJHMxwh3V7FPuT9Mr7Lj2IhVEUB16dcv1VNB0Nm0d4waP3zK8M2oDbguv%2Bv7KSbjHJix0zZT5id%2Fgc%3D&srcPrefix=%2Fko%2Fdocs%2FWeb%2FAPI%2FCanvas_API%2FTutorial%2FApplying_styles_and_colors%2F
      function drawMiterLimit() {
        ctx.clearRect(0, 420, 300, 300);

        // 기준선
        ctx.strokeStyle = "#09f";
        ctx.lineWidth = 2;
        ctx.strokeRect(0, 485, 230, 50);

        // 선 스타일을 설정한다
        ctx.strokeStyle = "#000";
        ctx.lineWidth = 8;
        // 입력 값을 검사한다
        if (document.getElementById("miterLimit").value.match(/\d+(\.\d+)?/)) {
          ctx.miterLimit = parseFloat(
            document.getElementById("miterLimit").value,
          );
        } else {
          alert("Value must be a positive number");
        }

        // 선을 그린다
        ctx.beginPath();
        ctx.moveTo(10, 480);
        for (i = 0; i < 24; i++) {
          var dy = i % 2 == 0 ? 25 : -25;
          ctx.lineTo(Math.pow(i, 1.5) * 2 + 10, 510 + dy);
        }
        ctx.stroke();
        return false;
      }
      document.getElementById("miterLimit").value = document
        .getElementById("canvas")
        .getContext("2d").miterLimit;
      drawMiterLimit();
    </script>
  </body>
</html>
  • 코드 결과

14-03 gradient

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Demo</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="600" height="200"></canvas>
    <script>
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");

      // createLinearGradient: 그라디언트가 시작할 위치와 끝날 위치
      // x축에선 그라디언트가 없고 y축에서만 그라디언트 생성
      let lingrad = ctx.createLinearGradient(0, 0, 0, 150);
      // addColorStop(offset: 시작점, color: 색)
      lingrad.addColorStop(0, "#00ABEB");
      lingrad.addColorStop(0.5, "#fff");
      lingrad.addColorStop(0.5, "#26C000");
      lingrad.addColorStop(1, "#fff");

      let lingrad2 = ctx.createLinearGradient(0, 50, 0, 95);
      lingrad2.addColorStop(0.5, "#000");
      lingrad2.addColorStop(1, "rgba(0, 0, 0, 0)");

      // 외곽선과 채움 스타일에 적용
      ctx.fillStyle = lingrad;
      ctx.strokeStyle = lingrad2;

      ctx.fillRect(10, 10, 130, 130);
      ctx.strokeRect(50, 50, 50, 50);

      // const radGrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30);
      // createRadialGradient(x1, y1, r1, x2, y2, r2): x1, y1, r1은 circle1에 대한, x2, y2, r2는 circle2에 대한 값
      // 개별 객체가 아닌 하나의 객체이기에 좌표의 차이가 원을 그릴 수 없으면 도형이 어그러짐
      // r2가 r1보다 크면 내원, 외원이 바뀜
      const radGrad = ctx.createRadialGradient(175, 25, 8, 182, 30, 25);
      radGrad.addColorStop(0, "#A7D30C");
      radGrad.addColorStop(0.9, "#019F62");
      // radGrad.addColorStop(1, "transparent"); // transparent: 투명
      radGrad.addColorStop(1, "transparent"); // transparent: 투명
      ctx.fillStyle = radGrad;
      // fillRect으로 하기에 transparent로 하지 않으면 다른 그림을 가림
      ctx.fillRect(150, 0, 150, 150);

      ctx.beginPath();
      const radGrad2 = ctx.createRadialGradient(175, 70, 8, 182, 85, 25);
      radGrad2.addColorStop(0, "#FF5F98");
      radGrad2.addColorStop(0.75, "#FF0188");
      radGrad2.addColorStop(1, "#c8c8c8"); // transparent: 투명
      ctx.fillStyle = radGrad2;
      // 크기를 맞추면 transparent가 아니어도 됨
      ctx.arc(182, 85, 25, 0, Math.PI * 2);
      ctx.fill();

      ctx.beginPath();
      const radGrad3 = ctx.createRadialGradient(255, 25, 8, 262, 30, 25);
      radGrad3.addColorStop(0, "#00C9FF");
      radGrad3.addColorStop(0.8, "#00B5E2");
      radGrad3.addColorStop(1, "#c8c8c8");
      ctx.fillStyle = radGrad3;
      ctx.arc(262, 30, 35, 0, Math.PI * 2);
      // 크기를 안 맞춰서 넘침
      ctx.fill();

      ctx.beginPath();
      const radGrad4 = ctx.createRadialGradient(255, 94, 13, 262, 85, 25);
      radGrad4.addColorStop(0, "#F4F201");
      radGrad4.addColorStop(0.8, "#E4C700");
      radGrad4.addColorStop(1, "white");
      ctx.fillStyle = radGrad4;
      // 크기를 맞추면 뒤에 그린게 위에 와서 이전 것을 덮음
      ctx.arc(262, 85, 35, 0, Math.PI * 2);
      ctx.fill();

      ctx.beginPath();
      // createConicGradient(startAngle, x, y): x, y 기준으로 방사형으로 그려짐
      const gradient = ctx.createConicGradient(0, 450, 100);
      gradient.addColorStop(0, "red");
      gradient.addColorStop(0.25, "orange");
      gradient.addColorStop(0.4, "yellow");
      gradient.addColorStop(0.75, "green");
      gradient.addColorStop(1, "blue");

      ctx.fillStyle = gradient;
      ctx.fillRect(350, 0, 200, 200);
    </script>
  </body>
</html>
  • 코드 결과

14-04 shadow and image

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Demo</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
      const ctx = document.getElementById("canvas").getContext("2d");

      // shadow
      ctx.shadowOffsetX = 3;
      ctx.shadowOffsetY = 3;
      ctx.shadowBlur = 2;
      // ctx.shadowColor = "rgb(255 0 0)";
      ctx.shadowColor = "rgb(255 0 0 / 60%)"; // rgba(255,0,0,0.6)과 같음

      ctx.font = "20px Times New Roman";
      ctx.fillStyle = "Black";
      ctx.fillText("Sample String", 5, 30);

      ctx.shadowOffsetX = 3;
      ctx.shadowOffsetY = 3;
      ctx.shadowBlur = 30; // 그림자를 크기만큼 브럴
      ctx.shadowColor = "#ff0000";
      ctx.fillText("Sample String", 5, 60);
      // 그림자 지우기용
      ctx.shadowColor = "transparent";
      ctx.shadowBlur = 0;
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 0;

      // images
      // createPattern
      const img = new Image();
      img.src =
        "https://images.pexels.com/photos/35575789/pexels-photo-35575789/free-photo-of-charming-fluffy-cat-posing-outdoors-on-a-wall.jpeg";

      img.onload = () => {
        // 이미지 크기 조정
        const tempCanvas = document.createElement("canvas");
        const tempCtx = tempCanvas.getContext("2d");
        tempCanvas.width = 50;
        tempCanvas.height = 50;
        // drawImage(image, dx, dy, dWidth, dHeight)
        tempCtx.drawImage(img, 0, 0, 50, 50);
        // createPattern(image, repetition: ["repeat", "repeat-x", "repeat-y", "no-repeat"])
        const pattern = ctx.createPattern(tempCanvas, "repeat");
        ctx.fillStyle = pattern;
        ctx.fillRect(150, 0, 150, 150);

        // 반복문으로 pattern 만들기
        for (let i = 0; i < 5; i++) {
          for (let j = 0; j < 3; j++) {
            ctx.drawImage(img, j * 50 + 310, i * 30, 50, 30);
          }
        }

        // Slicing
        // drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
        // ctx.drawImage(img, 50, 50, 600, 600, 0, 150, 150, 150);
        ctx.drawImage(img, 1150, 2500, 2400, 3500, 0, 200, 150, 200);
        ctx.drawImage(img, 200, 200, 150, 200);
      };
    </script>
  </body>
</html>
  • 코드 결과

14-05 transformation

  • 도형 변화인데 이게 두 번째로 중요한 듯
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Demo</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
      const ctx = document.getElementById("canvas").getContext("2d");
      // translating
      for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
          // save와 restore는 stack처럼 사용됨
          ctx.save();
          ctx.fillStyle = `rgb(${51 * i} ${255 - 51 * i} 255)`;
          ctx.translate(10 + j * 50, 10 + i * 50);
          ctx.fillRect(0, 0, 25, 25);
          ctx.restore();
        }
      }

      ctx.restore();
      ctx.save();
      ctx.translate(150, 0);
      for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
          ctx.fillStyle = `rgb(${51 * i} ${255 - 51 * i} 255)`;
          ctx.translate(10, 10);
          ctx.fillRect(0, 0, 25, 25);
        }
      }

      ctx.restore();
      ctx.save();
      ctx.translate(30, 110);
      // rotating
      ctx.fillStyle = "#0095DD";
      ctx.fillRect(30, 30, 100, 100);
      // rotate는 canvas 요소의 좌상단 기준으로 회전
      ctx.rotate((Math.PI / 180) * 25);

      ctx.fillStyle = "#4D4E53";
      ctx.fillRect(30, 30, 100, 100);
      ctx.restore();
      ctx.save();
      ctx.translate(30, 110);

      ctx.fillStyle = "#0095DD";
      ctx.fillRect(150, 30, 100, 100);

      ctx.translate(200, 80);
      ctx.rotate((Math.PI / 180) * 25);
      // 원위치로 이동하여 제자리에서 회전하게 보임
      ctx.translate(-200, -80);

      ctx.fillStyle = "#4D4E53";
      ctx.fillRect(150, 30, 100, 100);

      ctx.restore();
      ctx.save();
      // scale은 크기와 위치 모두 곱연산
      ctx.scale(20, 2);
      ctx.fillRect(10, 130, 10, 10);
      // ctx.fillRect(10, 10, 10, 10);

      ctx.restore();
      ctx.save();
      // scale은 크기와 위치 모두 곱연산
      ctx.translate(10, 300);
      ctx.scale(20, 2);
      ctx.fillStyle = "blue";
      // 현재 좌표와 생성 좌표를 기준으로 하여 0, 0로 생성하면 위치는 불변
      ctx.fillRect(0, 0, 10, 10);

      ctx.restore();
      ctx.save();

      // 반전
      ctx.scale(-1, 1);
      ctx.font = "48px serif";
      ctx.fillText("MDN", -120, 400);

      ctx.restore();
      ctx.save();
      ctx.scale(1, -1);
      ctx.font = "48px serif";
      ctx.fillStyle = "blue";
      ctx.fillText("MDN", 0, -410);

      // Transform
      ctx.resetTransform();
      const sin = Math.sin(Math.PI / 6);
      const cos = Math.cos(Math.PI / 6);
      ctx.translate(300, 400);
      let c = 0;
      for (let i = 0; i <= 12; i++) {
        c = Math.floor((255 / 12) * i);
        ctx.fillStyle = `rgb(${c} ${c} ${c})`;
        ctx.fillRect(0, 0, 100, 10);
        // x스케일, y기울기(skew), x기울기(skew), y스케일, x좌표, y좌표
        ctx.transform(cos, sin, -sin, cos, 0, 0);
      }
      // x스케일, y기울기(skew), x기울기(skew), y스케일, x좌표, y좌표
      ctx.fillStyle = "rgb(255 128 255 / 50%)";
      // 우측 분홍 정사각형
      ctx.setTransform(1, 0, 0, 1, 305, 350);
      ctx.fillRect(0, 50, 100, 100);
      // 중앙 분홍 마름모
      ctx.setTransform(-1, -1, 0, 1, 300, 350);
      ctx.fillRect(0, 50, 100, 100);
      // 좌측 분홍 마름모
      ctx.setTransform(-1, 0, -1, 1, 300, 350);
      ctx.fillRect(0, 50, 100, 100);
      ctx.resetTransform(); // ctx.resetTransform() == ctx.setTransform(1, 0, 0, 1, 0, 0);
      // resetTransform 사용하면 계속 save, restore할 필요 없음
    </script>
  </body>
</html>
  • 코드 결과

14-06 animation

이게 제일 중요함.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas Demo</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="300" height="300"></canvas>
    <script>
      const ctx = document.getElementById("canvas").getContext("2d");
      const sun = new Image();
      const moon = new Image();
      const earth = new Image();

      function init() {
        sun.src =
          "https://png.pngtree.com/png-clipart/20230518/original/pngtree-realistic-sun-illustration-png-image_9164511.png";
        moon.src =
          "https://png.pngtree.com/png-clipart/20250501/original/pngtree-high-resolution-photograph-of-the-full-moon-png-image_20917165.png";
        earth.src =
          "https://png.pngtree.com/png-clipart/20240416/original/pngtree-the-earth-globe-on-transparent-background-png-image_14833557.png";
        // 브라우저가 애니메이션을 알아서 잘 실행해주도록 함
        window.requestAnimationFrame(draw);
      }

      function draw() {
        ctx.clearRect(0, 0, 300, 300); // 지우지 않으면 이전 이미지가 남아 있음

        ctx.fillStyle = "rgb(0 0 0 / 40%)";
        ctx.strokeStyle = "rgb(0 153 255 / 40%)";
        // 기준점 중앙으로 설정
        ctx.translate(150, 150);

        // Earth
        // time을 기준으로 움직이게 만듦
        const time = new Date();
        // 중앙 기준으로 회전하게 (지구의 공전)
        ctx.rotate(
          ((2 * Math.PI) / 60) * time.getSeconds() +
            ((2 * Math.PI) / 60000) * time.getMilliseconds(),
        );
        // rotate 후 상대 경로(지구의 위치)를 기준점으로 만듦
        ctx.translate(105, 0);
        ctx.fillRect(0, -12, 40, 24); // shadow
        ctx.drawImage(earth, -15, -15, 30, 30);

        // Moon
        // 지구 기준으로 회전 (달의 공전)
        ctx.rotate(
          ((2 * Math.PI) / 6) * time.getSeconds() +
            ((2 * Math.PI) / 6000) * time.getMilliseconds(),
        );
        // rotate 후 상대 경로(달의 위치)를 기준점으로 만듦
        ctx.translate(0, 28.5);
        ctx.drawImage(moon, -3.5, -3.5, 12, 12);

        // 초기화
        ctx.resetTransform();

        ctx.beginPath();
        ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit
        ctx.stroke();

        // sun
        ctx.drawImage(sun, 120, 120, 60, 60);
        // 배경, 가장 먼저 그려도 동일함
        ctx.globalCompositeOperation = "destination-over"; // 뒤에 그림
        ctx.fillStyle = "rgba(20,20,20)";
        ctx.fillRect(0, 0, 300, 300);

        window.requestAnimationFrame(draw);
      }
      init();
    </script>
  </body>
</html>

출처: MDN 캔버스 튜토리얼
참고: chatGPT

profile
데이터, 풀스택

0개의 댓글