Skip to content
toylee blog
toylee blog

컴퓨터·IT 문제 해결과 최신 기술 정보

  • 홈
  • 컴퓨터 활용
  • 프로그래밍
    • 파이썬
    • 자바(Java)
    • Flutter
    • HTML
    • Linux
    • 워드프레스
  • 맥북
  • IT 일반
  • 블로그 소개
  • 문의하기
toylee blog

컴퓨터·IT 문제 해결과 최신 기술 정보

HTML5 Canvas 기능 대화형 그래픽 만드는 방법

toylee, 2023년 06월 25일

HTML5 Canvas는 웹 브라우저 내에서 멋진 대화형 그래픽을 만들 수 있는 강력한 도구입니다. 이 글에서는 HTML5 Canvas 기능 대화형 그래픽을 만드는 방법에 대한 실제 예시를 보여줍니다. 어렵지 않으니 코드를 보면서 차근차근 글을 읽어 보시고, 따라오시면 됩니다. 자 그럼 시작해 볼까요?

[목차]

  • 캔버스 설정
  • 기본 도형 그리기
  • 애니메이션 만들기
  • 사용자 상호 작용 처리
  • 전체코드 보기
  • 결론

캔버스 설정

HTML5 Canvas를 사용하려면 웹 페이지 내에서 <canvas> 태그를 설정해야 합니다. 이 태그는 JavaScript를 통해 스타일을 지정하고 제어할 수 있는 캔버스 영역을 정의합니다.

<canvas id="myCanvas" width="800" height="600"></canvas>

기본 도형 그리기

캔버스 API를 사용하면 선, 사각형, 원, 다각형 등 다양한 도형을 그릴 수 있습니다. 다음은 몇 가지 기본적인 예시입니다.

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// 선 그리기
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 50);
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.stroke();

// 사각형 그리기
ctx.fillStyle = "blue";
ctx.fillRect(50, 100, 150, 100);

// 원 그리기
ctx.beginPath();
ctx.arc(400, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();

애니메이션 만들기

HTML5 Canvas를 사용하면 캔버스 콘텐츠를 지속적으로 업데이트하여 매력적인 애니메이션을 만들 수 있습니다. 이는 requestAnimationFrame 함수를 사용하고 각 프레임 내에서 캔버스를 업데이트하여 달성됩니다.

function animate() {
  // 캔버스 지우기
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 위치 업데이트
  x += dx;
  y += dy;

  // 새 위치에서 모양 그리기
  ctx.beginPath();
  ctx.arc(x, y, 20, 0, 2 * Math.PI);
  ctx.fillStyle = "orange";
  ctx.fill();

  // 경계 확인 및 방향 전환
  if (x + dx > canvas.width || x + dx < 0) {
    dx = -dx;
  }
  if (y + dy > canvas.height || y + dy < 0) {
    dy = -dy;
  }

  // 다음 애니메이션 프레임 요청
  requestAnimationFrame(animate);
}

// 초기 위치 및 속도
let x = 100;
let y = 100;
let dx = 2;
let dy = 2;

// 애니메이션 시작
animate();

사용자 상호 작용 처리

HTML5 Canvas를 사용하면 마우스 이동 및 클릭과 같은 사용자 상호 작용을 캡처하여 대화형 그래픽을 만들 수 있습니다. 다음은 사용자가 모양을 클릭할 때 모양의 색상을 변경하는 예입니다.

// 캔버스에 클릭 이벤트 리스너 추가
canvas.addEventListener("click", function (event) {
  const rect = canvas.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;

  if (ctx.isPointInPath(mouseX, mouseY)) {
    ctx.fillStyle = getRandomColor();
  }
});

// 랜덤 색상 생성
function getRandomColor() {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

전체코드 보기

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<!DOCTYPE html>
<html>
<head>
  <title>HTML5 Canvas: Creating Interactive Graphics</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <h1>HTML5 Canvas: Creating Interactive Graphics</h1>
  <canvas id=“myCanvas” width=“800” height=“600”></canvas>
 
  <script>
    // Drawing Basic Shapes
    const canvas = document.getElementById(“myCanvas”);
    const ctx = canvas.getContext(“2d”);
 
    // Draw a line
    ctx.beginPath();
    ctx.moveTo(50, 50);
    ctx.lineTo(200, 50);
    ctx.strokeStyle = “red”;
    ctx.lineWidth = 2;
    ctx.stroke();
 
    // Draw a rectangle
    ctx.fillStyle = “blue”;
    ctx.fillRect(50, 100, 150, 100);
 
    // Draw a circle
    ctx.beginPath();
    ctx.arc(400, 200, 50, 0, 2 * Math.PI);
    ctx.fillStyle = “green”;
    ctx.fill();
 
    // Creating Animations
    let x = 100;
    let y = 100;
    let dx = 2;
    let dy = 2;
 
    function animate() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
 
      x += dx;
      y += dy;
 
      ctx.beginPath();
      ctx.arc(x, y, 20, 0, 2 * Math.PI);
      ctx.fillStyle = “orange”;
      ctx.fill();
 
      if (x + dx > canvas.width || x + dx < 0) {
        dx = –dx;
      }
      if (y + dy > canvas.height || y + dy < 0) {
        dy = –dy;
      }
 
      requestAnimationFrame(animate);
    }
 
    animate();
 
    // Handling User Interactions
    canvas.addEventListener(“click”, function (event) {
      const rect = canvas.getBoundingClientRect();
      const mouseX = event.clientX – rect.left;
      const mouseY = event.clientY – rect.top;
 
      if (ctx.isPointInPath(mouseX, mouseY)) {
        ctx.fillStyle = getRandomColor();
      }
    });
 
    function getRandomColor() {
      const letters = “0123456789ABCDEF”;
      let color = “#”;
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
  </script>
</body>
</html>
 
Colored by Color Scripter
cs

실행화면

HTML5 Canvas

HTML5 Canvas: Creating Interactive Graphics

HTML5 Canvas: Creating Interactive Graphics

결론

HTML5 Canvas를 사용하면 웹 브라우저 내에서 창의적인 대화형 그래픽을 만들 수 있습니다. 이 글에서 다룬 예시와 개념을 통해 HTML5 Canvas의 가능성을 탐색할 수 있는 견고한 기반을 갖추게 되었습니다. 이제 HTML5 Canvas를 사용하여 창의력을 발휘하고 매력적인 대화형 그래픽을 사용하시기 바랍니다.

[관련글]

all html tag 설명 및 예제
Flex Css display 주요기능

파이썬 웹크롤링(crawling), PyQt6, BeautifulSoup

파이썬 문자열 합치기(join(), format() 외)

HTML5 란?

HTML

글 탐색

Previous post
Next post

Related Posts

HTML 검색 결과의 제목과 요약문 구성을 검토하는 작업 장면을 표현한 연출 이미지

meta description 작성 팁: 검색 결과 클릭률을 높이는 요약문 작성 방법

2026년 09월 18일

웹사이트 검색 유입을 늘리기 위해 중요한 메타 설명 태그의 기본 개념과 초보자가 쉽게 따라 할 수 있는 작성 요령을 정리합니다.

Read More
HTML

Techniques for Compressing Websites to Improve Performance

2023년 07월 15일

Website performance is crucial as users will abandon slow websites. Therefore, web developers use various techniques to optimize websites for user experience. Among these techniques, website compression is highly effective in reducing website loading time. Techniques for Compressing Websites Website compression involves reducing the size of website files. It does…

Read More
HTML

HTML은 프로그래밍 언어가 아닙니다. 이유

2023년 06월 05일

웹 페이지를 구성하는 언어 중 하나인 HTML은 웹 개발의 기초를 이루는 중요한 요소입니다. 그러나 HTML은 프로그래밍 언어가 아닙니다. 이번 글에서는 HTML이 무엇인지, 어떻게 작동하는지, 그리고 HTML의 역할과 중요성에 대해 알아보도록 하겠습니다.

Read More

최신 글

  • 워드프레스 스팸 댓글 관리 기본 설정 및 차단 대처 요령
  • 파이썬 CSV 자동 정리 스크립트 작성법: 데이터 전처리 요령
  • 브라우저 캐시 삭제가 필요한 경우와 상황별 대처 요령 정리
  • 맥북 발열 줄이는 기본 설정: 성능 저하를 막는 실무 관리 요령
  • 에러 로그 읽는 습관 만들기: 개발 속도를 높이는 오류 분석 요령

최신 댓글

보여줄 댓글이 없습니다.

보관함

  • 2026년 10월
  • 2026년 9월
  • 2026년 8월
  • 2026년 2월
  • 2025년 7월
  • 2025년 6월
  • 2025년 5월
  • 2025년 4월
  • 2025년 3월
  • 2025년 2월
  • 2025년 1월
  • 2024년 12월
  • 2024년 11월
  • 2024년 8월
  • 2024년 6월
  • 2024년 5월
  • 2024년 3월
  • 2024년 2월
  • 2023년 11월
  • 2023년 9월
  • 2023년 8월
  • 2023년 7월
  • 2023년 6월
  • 2023년 5월
  • 2023년 4월
  • 2023년 3월
  • 2023년 2월

카테고리

  • Flutter
  • HTML
  • IT 일반
  • Linux
  • 맥북
  • 워드프레스
  • 자바(Java)
  • 컴퓨터 활용
  • 파이썬
  • 프로그래밍

사이트 안내

  • 블로그 소개
  • 문의하기
  • 개인정보 처리방침
©2026 toylee blog | WordPress Theme by SuperbThemes