반응형
canvas 엘리먼트는 javascript에 그래픽을 그릴 수 있는 API다.
사용방법은 간단하다.
html에는 <canvas></canvas> 라고 작성하는 게 끝.
그 다음 그래픽을 그리기 위한 모든 작업은 javascript에서 canvas 엘리먼트에 접근한 후 이루어진다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>meme-maker</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas></canvas>
<script src="app.js "></script>
</body>
</html>
styles.css
body {
display: flex;
justify-content: center;
align-items: center;
}
canvas {
width: 800px;
height: 800px;
border: 5px solid black;
display: flex;
justify-content: end;
}
#1.2 사각형을 그리기 위한 단계
- 사각형 테두리 그리기: ctx.rec(x, y, with, height);
- ctx.stroke() 하여 테두리의 색을 주거나 ctx.fill() 로 사각형을 채울 수 있다.
*그린 사각형은 모두 하나의 경로를 적용받기 때문에 색상을 변경하면 여태 그린 사각형들이 한꺼번에 바뀐다.
분리하고 싶다면 경로를 새로 시작해주면 된다. -> ctx.beginPath();
app.js
const canvas = document.querySelector("canvas"); /** canvas라는 변수는 html의 canvas라는 엘리먼트를 지정한다 */
const ctx = canvas.getContext("2d"); /** 2d로 그릴 것을지정 ctx는 canvas에 그림 그릴 때 쓰는 것 */
canvas.width = 800;
canvas.height = 800;
ctx.rect(50, 50, 100, 100);
ctx.rect(150, 150, 100, 100);
ctx.rect(250, 250, 100, 100);
ctx.fill();
ctx.beginPath(); /** 경로 새로 시작하기. 위의 3개 사각형과 아래 사각형의 경로가 달라진다. */
ctx.rect(350, 350, 100, 100);
ctx.rect(450, 450, 100, 100);
ctx.fillStyle="red";
ctx.fill();
결과 (화면출력)
반응형
'IT > javascript' 카테고리의 다른 글
[자바스크립트] canvas 그림판 선 긋기, 점 찍기, 색상변경 / offsetX, offsetY, lineWidth, strokeStyle, (1) | 2022.11.03 |
---|---|
[자바스크립트] moveTo() lineTo()란? 사각형, 삼각형, 집 그리기 / 바닐라JS 그림 앱 만들기 / #1.3 #1.4 (0) | 2022.11.03 |
[mongoose] Schema 스키마, Model 이란? 스키마와 모델 작성하기 (유튜브 클론 6.9, 6.10) (1) | 2022.09.20 |
mongoose 몽구스 설치하고 DB연결하기. (유튜브 클론 6.8) (0) | 2022.09.19 |
[macOS] MongoDB 설치하기 (유튜브 클론 6.7) (0) | 2022.09.16 |