Gitsunmin

TIL

TIL
(=Today I Learned)

Canvas API

설명

Canvas API는 HTML5에서 새롭게 추가된 기능으로, HTML5에서 동적으로 그래픽을 그릴 수 있게 해준다. Canvas API는 2D 그래픽을 그리는 CanvasRenderingContext2D와 3D 그래픽을 그리는 WebGLRenderingContext로 구성되어 있다.

사용법

1. 객체 생성

index.html

<canvas id="canvas" width="500" height="500"></canvas>

index.js

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

2. 선 그리기

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();

3. 원 그리드

ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, true);
ctx.stroke();

4. 사각형 그리기

ctx.beginPath();
ctx.rect(100, 100, 100, 100);
ctx.stroke();

5. 이미지 그리기

const img = new Image();
img.src = 'image.png';
img.onload = function() {
    ctx.drawImage(img, 100, 100);
};

6. 텍스트 그리기

ctx.font = '20px Arial';
ctx.fillText('Hello World!', 100, 100);

7. 색상 설정

ctx.fillStyle = 'red';
ctx.strokeStyle = 'blue';

8. 투명도 설정

ctx.globalAlpha = 0.5;

9. 그림자 설정

ctx.shadowColor = 'black';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 5;

10. 선 스타일 설정

ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.miterLimit = 10;

11. 캔버스 초기화

ctx.clearRect(0, 0, canvas.width, canvas.height);

12. 캔버스 저장

ctx.save();

13. 캔버스 복원

ctx.restore();

14. 캔버스 크기 설정

canvas.width = 500;
canvas.height = 500;

15. 캔버스 크기 가져오기

const width = canvas.width;
const height = canvas.height;

16. 캔버스 스타일 설정

canvas.style.border = '1px solid black';

17. 캔버스 위치 설정

canvas.style.position = 'absolute';
canvas.style.left = '100px';
canvas.style.top = '0px';

18. 캔버스 이벤트 설정

canvas.addEventListener('click', function(e) {
    const x = e.offsetX;
    const y = e.offsetY;
});

19. 캔버스 애니메이션

const x = 100;
const y = 100;

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(x, y, 50, 0, Math.PI * 2, true);
    ctx.stroke();
    requestAnimationFrame(draw);
}

requestAnimationFrame(draw);