본문 바로가기
JavaScript

[JavaScript] Canvas API

by 기록하는_사람 2022. 10. 24.

CANVAS API

📌 CANVAS API

: Javascript로 그래픽을 그릴 수 있게 하는 API.

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

 

CANVAS API - context

📌 context

: 그림 그릴 때 사용. 

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

 

💡 왼쪽 상단 : (0, 0)

 

📌 context의 function

.fillRect(x, y, w, h) 색 채운 사각형 그림.
.rect(x, y, w, h) 사각형 생성.
.fill() 단색으로 채움.
.stroke() 선만 그림. 
.fillStyle 색 설정.  

 

CANVAS API - path

📌 path

: 새로운 경로를 설정하지 않으면, 모두 같은 경로임.

  같은 경로에 있는 것들은 같이 적용됨.

 

📌 context.beginPath()

: 새로운 경로 생성. 

 

CANVAS API - moveTo, lineTo

📌 moveTo(x, y)

: 브러쉬 위치 이동. 

 

📌 lineTo(x, y)

: 현재 위치에서 (x, y)로 선 그림.

 

📄 집 그리기

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 800;
canvas.height = 800;

ctx.fillRect(200, 200, 50, 200);
ctx.fillRect(400, 200, 50, 200);

ctx.lineWidth = 2;
ctx.strokeRect(300, 300, 50, 100);

ctx.fillRect(200, 200, 200, 20);

ctx.moveTo(200, 200);
ctx.lineTo(325, 100);
ctx.lineTo(450, 200);
ctx.fill();

📄 사람 그리기

const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 800;
canvas.height = 800;

ctx.fillRect(210 - 40, 200 - 30, 15, 100);
ctx.fillRect(350 - 40, 200 - 30, 15, 100);

ctx.fillRect(260 - 40, 200 - 30, 60, 200);

ctx.arc(250, 100, 50, 0, 2 * Math.PI);
ctx.fill();

ctx.beginPath();
ctx.fillStyle = "white"
ctx.arc(260 + 10, 80, 8, Math.PI, 2 * Math.PI);
ctx.arc(220 + 10, 80, 8, Math.PI, 2 * Math.PI);
ctx.fill();

'JavaScript' 카테고리의 다른 글

[JavaScript] JavaScript와 CSS  (0) 2022.10.14
[JavaScript] Event  (0) 2022.10.14
[JavaScript] document  (0) 2022.10.14
[JavaScript] conditional  (0) 2022.10.13
[JavaScript] prompt와 형 변환  (0) 2022.10.13

댓글