자바스크립트와 캔버스 (D-86)

최우정·2022년 6월 27일
0

100일

목록 보기
15/17
post-thumbnail

📒 01. 캔버스 요소

  • 캔버스는 <canvas> 요소로 생성

  • 캔버스는 HTML 페이지 상에서 사각형태의 영역

  • 실제 그림은 자바스크립트를 통하여 코드로 그려야 한다.

✏️ 캔버스 생성

<canvas id="myCanvas" width="300" height="100"></canvas>

✏️ 컨텍스트(context) 객체

  • 자바스크립트에서 물감과 붓의 역할을 한다.

var canvas = document.getElementById("myCanvas");

var context = canvas.getContext("2d");

✏️ 간단한 그림 그리기

canvas1.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <!-- 캔버스 요소를 정의한다. -->
  <canvas id="myCanvas" width="200" height="100"
  style="border: 1px dotted red"></canvas>
  <script>
    // 먼저 캔버스 요소를 찾는다.
    var canvas = document.getElementById("myCanvas");
    // 캔버스에서 컨텍스트를 얻는다.
    var context = canvas.getContext("2d");
    context.fillStyle = "#00FF00";
    // 캔버스 위에 사각형을 그린다.
    context.fillRect(0, 0, 100, 50);
  </script>
</body>
</html>

직선 그리기

canvas_line.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    body {
      margin: 0px;
      padding: 0px;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="300" height="200"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

	// 경로를 초기화 한다.
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(100, 100);
    context.lineTo(150, 50);
    context.lineTo(200, 100);
    context.stroke();
  </script>
</body>
</html>

사각형 그리기

canvas_rect.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="300" height="300"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.rect(10, 10, 100, 100);
    context.rect(50, 50, 100, 100);
    context.stroke();
  </script>
</body>
</html>

채워진 사각형을 그리고 싶으면 stroke() 대신에 fill()을 호출하면 된다.

canvas_rect1.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="300" height="300"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.rect(10, 10, 100, 100);
    // 채우기 속성을 노란색으로 지정한다.
    context.fillStyle="yellow";
    context.fill();
    context.rect(50, 50, 100, 100);
    context.stroke();
  </script>
</body>
</html>

✏️ 원 그리기

캔버스에 원을 그리기 위해서는 arc() 메서드를 사용한다.

arc(x, y, radius, startAngle, endAngle, anticlockwise)

(x, y)를 중심으로 반지름이 radius인 원을 그린다.

start는 시작각도, end는 종료각도이다.

canvas_arc.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.arc(100, 100, 80, 0, 2.0*Math.PI, false);
    context.strokeStyle = "red";
    context.stroke();

    context.beginPath();
    context.arc(100, 100, 60, 0, 1.5*Math.PI, false);
    context.closePath();
    context.strokeStyle = "blue";
    context.stroke();

    context.beginPath();
    context.arc(100, 100, 40, 0, 1.5*Math.PI, false);
    context.strokeStyle = "green";
    context.stroke();

  </script>
</body>
</html>

✏️ 곡선 그리기

베지어 곡선 같은 3차 곡선도 그릴 수 있다. 베지어 곡선은 4개의 제어점 안에 그려지는 3차 곡선이다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(90, 130);
    context.bezierCurveTo(140, 10, 288, 10, 288, 130);
    context.lineWidth = 10;

    context.strokeStyle = 'black';
    context.stroke();
  </script>
</body>
</html>

✏️ 일반적인 도형 그리기

일반적인 도형은 경로(path)를 형성해서 그리면 된다.

경로는 beginPath() 호출로 시작해서 closePath() 호출로 종료한다.

canvas_path.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(50, 100);
    context.lineTo(75, 50);
    context.lineTo(100, 100);
    context.closePath();
    context.fillStyle = "green";
    context.fill();
  </script>
</body>
</html>

✏️ 텍스트 그리기

캔버스에 텍스트를 그리기 위해서는 다음과 같은 속성의 메서드를 사용한다.

  • font: 텍스트를 그리는데 사용되는 폰트 속성을 정의한다.

  • fillText(text, x, y): 캔버스에 채워진 텍스트를 그린다.

  • strokeText(text, x, y): 캔버스에 텍스트의 외곽선만을 그린다.

canvas_text.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.font = 'italic 38pt Arial';
    context.fillText('Hello World', 20, 100);
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.font = 'italic 38pt Arial';
    context.strokeText('Hello World!', 20, 100);
  </script>
</body>
</html>

📒 02. 도형의 속성

✏️ 선 그리기 속성

  • context.lineWidth: 선의 두께를 지정한다.
  • context.strokeStyle: 선의 색상을 지정한다.
  • context.lineCap: 선의 양쪽 끝점의 모양을 지정한다. (butt, round, square 중의 하나이다.)

canvas_line_prop.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    var c = document.getElementById('myCanvas');
    var ctx = c.getContext('2d');

    ctx.beginPath();
    ctx.lineWidth = 20;
    ctx.lineCap = "round";
    ctx.moveTo(20, 20);
    ctx.lineTo(200, 20);
    ctx.stroke();
  </script>
</body>
</html>

✏️ 그라디언트로 채우기

  • createLinearGrandient(x, y, x1, y1) : 선형 그라디언트를 생성한다.
  • createRadialGrandient(x, y, r, x1, y1, r1): 원형 그리디언트를 생성한다.
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var gradient = context.createLinearGradient(0, 0, 200, 0);
    gradient.addColorStop(0, "white");
    gradient.addColorStop(1, "red");

    context.fillStyle = gradient;
    context.fillRect(10, 10, 180, 90);
  </script>
</body>
</html>

canvas_gra1.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var gradient = context.createRadialGradient(70, 50, 10, 80, 60, 120);
    gradient.addColorStop(0, "white");
    gradient.addColorStop(1, "red");

    context.fillStyle = gradient;
    context.fillRect(10, 10, 180, 90);
  </script>
</body>
</html>

✏️ 패턴으로 채우기

createPattern() 메서드를 이용한다.

canvas_pattern.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="300" height="300"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var image = new Image();
    image.src = "pattern.png";
    image.onload = function() {
      var pattern = context.createPattern(image, "repeat");

      context.rect(0, 0, canvas.width, canvas.height);
      context.fillStyle = pattern;
      context.fill();
    }
  </script>
</body>
</html>

✏️ 이미지 그리기

drawImage() 메서드를 이용한다.

canvas_image.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="300" height="300"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var image = new Image();
    image.src = "html5_logo.png";

    image.onload = function() {
      context.drawImage(image, 0, 0);
    };
  </script>
</body>
</html>

📒 03. 도형 변환

HTML5에서는 2차원 변환인 평행이동(translation), 신축(scaling), 회전(rotation)을 비롯한 모든 변환을 지원한다.

✏️ 평행 이동

canvas_trans.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <canvas id="myCanvas" width="600" height="400"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.fillStyle = "blue";
    context.fillRect(0, 0, 100, 100);

    // 좌표계를 평행 이동 시킨다.
    context.translate(50, 50);
    context.fillStyle = "red";
    context.fillRect(0, 0, 100, 100);
  </script>
</body>
</html>

📒 04. 애니메이션

✏️ Bouncing Ball

  1. 캔버스를 지운다.

context.clearRect(0, 0, 300, 200);

  1. (x, y) 위치에 그림을 그린다.
context.beginPath();
context.fillStyle = "red";
context.arc(x, y, 20, 0, Math.PI*2, true);
context.closePath();
context.fill();
  1. 위치를 업데이트 한다.
x += dx;
y += dy;

반사되는 코드

if (x < (0 + 20) || x > (300 - 20))
	dx = -dx;
if (y < (0 + 20) || y > (200 - 20))
	dy = -dy;
x += dx;
y += dy;
  1. 위의 절차(1부터 3까지)를 반복한다.
setTimeout(doSomething, 500); // 500밀리초 후에 doSomething()을 호출한다.
setInterval(doSomething, 500); // 매 500밀리초마다 doSomething()을 호출한다.

canvas_ball.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Bouncing Ball Example</title>
  <style>
    canvas {
      background: yellow;
      border: 1px dotted black;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="300" height="200"></canvas>
  <script>
    var context;
    var dx = 5; // 볼이 한 번에 움직이는 거리
    var dy = 5;
    var y = 100;
    var x = 100;
    function draw() {
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      context.clearRect(0, 0, 300, 200);
      context.beginPath();
      context.fillStyle = "red";
      context.arc(x, y, 20, 0, Math.PI*2, true); // 공을 그린다.
      context.closePath();
      context.fill();
      if (x < (0 + 20) || x > (300 - 20)) // 공이 벽에 닿음 반사시킨다.
      dx = -dx;
      if (y < (0 + 20) || y > (200 - 20))
      dy = -dy;
      x += dx;
      y += dy;
    }
    setInterval(draw, 10); // 10 밀리초마다 draw()를 호출한다.
  </script>
</body>
</html>

profile
비전공자 Java, JavaScript, Html, Css, C++ 공부중

0개의 댓글