기타

canvas 태그 사용하기

citron031 2023. 6. 23. 23:42

canvas 태그는 HTML5에서 도입된 요소이다.

자바스크립트를 사용하여 동적으로 그래픽을 컨트롤할 수 있게 해준다.

canvas 태그를 사용하면, 자바스크립트로 선, 도형, 이미지, 텍스트를 그리고 스타일을 지정할 수 있다.

프레임 기반 애니메이션 및 인터랙티브 기능(마우스 클릭, 키보드 입력 등)을 제공한다.

 

기본적인 사용법은 다음과 같다.

<canvas id="test-canvas"></canvas>

위와 같은 HTML 파일을 아래의 자바스크립트 코드로 조작한다.

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

ctx.fillStyle = "#ccc";
// top left width height
ctx.fillRect(10, 10, 50, 100);

회색 직사각형이 그려진 것을 확인할 수 있다.

 

뿐만 아니라, 이미지를 canvas 태그에 삽입할 수도 있다.

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

const image = new Image();
image.src = 'https://picsum.photos/id/237/200/300';

image.onload = () => {
  // img, top, left, width, height
  ctx.drawImage(image, 0, 0, 300, 200);  
}

 

 

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API

 

Canvas API - Web APIs | MDN

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

 

CanvasRenderingContext2D: drawImage() method - Web APIs | MDN

The CanvasRenderingContext2D.drawImage() method of the Canvas 2D API provides different ways to draw an image onto the canvas.

developer.mozilla.org