캔버스(Canvas) API
- 캔버스는 픽셀 기반의 비트맵 이미지와 벡터 그래픽(svg)을 처리하는 기능
- 캔버스 태그 사용 시 필수 속성: id, width, height
스타일에서 너비/높이 설정의 한계
CSS로 크기 지정 시 위치 오차 발생 위치 오차: 캔버스 내 요소가 이동한 후 위치 불일치
// 캔버스 환경 설정 및 작업 수행
const canvasElement = document.getElementById("myCanvas");
const ctx = canvasElement.getContext("2d");
// 작업 대상 객체(ctx)를 통해 다양한 메서드 호출 가능
주요 메서드 및 속성
fillRect(x,y,w,h): 페인팅 모드로 사각형 생성 (기본 색상: 검정) fillStyle: 채움 색상 설정 (예: '#FF0000')
strokeRect(x,y,w,h): 경계선만 그려짐 (경계선 두께 2px로 인해 좌표 조정 필요) lineWidth: 선두께 조절 strokeStyle: 선색상 설정
lineJoin: 선 연결 방식 (round: 둥글게 연결) textBaseline: 텍스트 기준선 설정
선 그리기
moveTo(x,y): 시작점 설정 lineTo(x,y): 종료점 설정 (다중 lineTo 사용 가능) stroke(): 선 완성
beginPath() - 경로 시작 closePath() - 경로 닫기 rect(x,y,w,h): 경계선만 있는 사각형 clearRect(x,y,w,h): 특정 영역 제거
save()/restore(): 스타일 범위 제어 (내부 영향만 적용)
원 그리기
arc(x,y,radius,startAngle,endAngle,anticlockwise): 원 생성 translate(x,y): 캔버스 이동 (크기 유지) rotate(angle): 회전 (이동 후 회전 권장) scale(factorX,factorY): 확대/축소 (시야 거리 변경)
이미지 삽입
const img = new Image();
img.src = "image.png";
img.onload = () => {
ctx.drawImage(img, x, y, width, height);
}
텍스트 처리
strokeText(text,x,y): 테두리 있는 텍스트 fillText(text,x,y): 테두리 없는 텍스트 textAlign: 수평 정렬 (center: 중앙 정렬) textBaseline: 수직 정렬 (middle: 중앙 정렬) font: 폰트 크기 및 스타일 설정
웹 스토리지 기능
로컬/세션 스토리지 특징
localStorage: 클라이언트에 영구 저장 (수동 삭제 전까지 유효) sessionStorage: 세션 기간 동안 유효 (브라우저 종료 시 자동 삭제)
데이터 형식: 모두 문자열로 저장됨
시간 기반 저장 구현
// 데이터 저장 함수
function saveData(key, value, expiration) {
const data = { key, value, timestamp: Date.now() };
if (expiration) {
data.expires = expiration;
}
localStorage.setItem(key, JSON.stringify(data));
}
// 데이터 조회 함수
function loadData(key) {
const item = localStorage.getItem(key);
if (!item) return null;
try {
const parsed = JSON.parse(item);
if (parsed.timestamp && parsed.expires) {
if (Date.now() - parsed.timestamp > parsed.expires) {
localStorage.removeItem(key);
return null;
}
}
return parsed.value;
} catch (e) {
return null;
}
}
웹워커 및 웹소켓 기능
웹워커 특징
- 배경에서 실행되는 독립적 JavaScript 스레드
- 복잡한 계산 작업 시 주 스레드 차단 방지
- postMessage()를 통한 데이터 전달
웹소켓 프로토콜
ws://(보안x), wss://(보안o)
- 양방향 실시간 통신 가능
- HTTP와 달리 서버/클라이언트 상호 정보 전송
웹소켓 연결 예시
const webSocketInstance = new WebSocket('wss://example.com/socket');
webSocketInstance.onopen = () => {
webSocketInstance.send('Client initialization message');
webSocketInstance.onmessage = (event) => {
console.log('Received:', event.data);
};
webSocketInstance.onclose = (event) => {
console.log('Connection closed:', event.reason);
};
};