-
TIL-2024.04.20 - Canvas - 002 - Canvas 그리기> Frontend/Canvas 2024. 4. 21. 23:16
질문:
1. Canvas에서 그리기를 어떻게 구현할 수 있어 ?
Canvas 엘리먼트 생성하기:
- Canvas 엘리먼트를 생성하고 JavaScript를 사용하여 그래픽을 그리는 방법
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas 엘리먼트 생성</title> </head> <body> <canvas id="myCanvas" width="400" height="200"></canvas> </body> </html>
> canvas 엘리먼트를 생성하고, id 속성을 통해 이 엘리먼트를 JavaScript에서 식별
Context(컨텍스트)와 그리기 명령:
- Canvas는 그리기 명령을 처리하기 위해 2D 그래픽 컨텍스트를 제공
JavaScript로 Canvas 컨텍스트
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
그리기 명령 사용
// 사각형 그리기 ctx.fillStyle = 'red'; // 색상 설정 ctx.fillRect(50, 50, 100, 80); // (x, y, width, height) // 선 그리기 ctx.strokeStyle = 'blue'; // 선 색상 설정 ctx.lineWidth = 2; // 선 두께 설정 ctx.beginPath(); ctx.moveTo(200, 50); // 시작점 설정 ctx.lineTo(300, 100); // 끝점 설정 ctx.stroke(); // 선 그리기 // 원 그리기 ctx.fillStyle = 'green'; // 색상 설정 ctx.beginPath(); ctx.arc(350, 150, 30, 0, 2 * Math.PI); // (x, y, radius, startAngle, endAngle) ctx.fill(); // 원 내부 채우기
Canvas 좌표계와 픽셀 처리:
- Canvas는 좌상단 모서리가 (0, 0)이고, x축은 오른쪽으로, y축은 아래쪽으로 증가하는 좌표계를 사용
// 점 그리기 ctx.fillStyle = 'black'; ctx.fillRect(10, 10, 1, 1); // (x, y, width, height) // 픽셀 데이터 다루기 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = imageData.data; // 픽셀 데이터 배열 // 예제: Canvas 픽셀 색상 변경 for (let i = 0; i < data.length; i += 4) { // 픽셀 데이터를 수정하여 색상을 반전시킵니다. data[i] = 255 - data[i]; // 빨강 data[i + 1] = 255 - data[i + 1]; // 초록 data[i + 2] = 255 - data[i + 2]; // 파랑 // data[i + 3] (알파 값)은 변경하지 않습니다. } ctx.putImageData(imageData, 0, 0); // 변경된 픽셀 데이터를 Canvas에 적용
- Canvas의 픽셀 데이터는 getImageData 메서드를 사용하여 읽어옴.
- getImageData는 특정 영역의 픽셀 데이터를 가져오며, 각 픽셀은 빨강, 초록, 파랑, 알파(투명도) 값으로 구성된 배열로 표현.
- 이러한 픽셀 데이터를 직접 수정하여 Canvas에 적용 가능.
'> Frontend > Canvas' 카테고리의 다른 글
TIL-2024.04.23 - Canvas - 005 - Canvas 애니메이션 & 이벤트 (0) 2024.04.23 TIL-2024.04.22 - Canvas - 004 - Canvas 텍스트 & 이미지 (0) 2024.04.22 TIL-2024.04.21 - Canvas - 003 - Canvas 곡선 그리기 (0) 2024.04.21 TIL-2024.04.19 - Canvas - 001 - Canvas 기초 (0) 2024.04.20