본문 바로가기
Programming

Canvas 위에 네모 그리는 방법

by 혀코 2023. 6. 9.

HTML의 canvas 태그를 사용해서 웹사이트에 네모를 그리는 방법에 대해서 알아보겠습니다.

Index.html 파일을 다음과 같이 작성합니다.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>canvas 사용해서 네모그리기</title>
  <link rel="stylesheet" href="style.css" />
  <script type="module" src="nemo.js" defer></script>
</head>
<body>
  <canvas></canvas>
</body>
</html>

body 태그 안에 canvas 태그를 넣어주고 수정할 CSS 파일과 JS 파일을 head 태그 안에 작성해 줍니다.

 

style.css 파일을 다음과 같이 작성해서 canvas에 배경색을 넣어줍니다.

너비와 높이 따로 지정을 하지 않아도 표시가 됩니다. 기본값은 가로 150 그리고 세모 100입니다.

nemo.js 파일을 다음과 같이 작성해서 네모를 그려줍니다. 

const canvas = document.querySelector('canvas')

const ctx = canvas.getContext('2d')

ctx.fillRect(10, 10, 50, 50)

ctx.fillRect는 4개의 parameter가 있습니다. 왼쪽부터 오른쪽으로 순서대로 그려질 네모의 x좌표 및 y좌표 가로길이, 세로길이를 의미합니다.

위와 같이 직사각형 canvas위에 위와 왼쪽으로부터 10 px 떨어진 곳에 가로 세로 50 px의 네모가 그려진 것을 확인할 수 있습니다.

이 상태에서 직사각형 canvas의 가로 세로를 한변당 300px의 정사각형으로 바꿔보도록 하겠습니다. 

const canvas = document.querySelector('canvas')

const ctx = canvas.getContext('2d')

canvas.style.width = 300 + 'px'
canvas.style.height = 300 + 'px'

ctx.fillRect(10, 10, 50, 50)

먼저 그렸던 정사각형 네모가 위아래로 길어진 직사각형으로 변한 것을 확인할 수 있습니다.

그 이유는 style을 통해 기본 canvas의 사이즈인 300 x 150 사이즈를 위아래로 300 x 300 사이즈로 늘렸기 때문입니다.

 

style이 아니라 canvas 의 가로 세로 사이즈를 300 x 300 사이즈로 맞춰보겠습니다.

const canvas = document.querySelector('canvas')

const ctx = canvas.getContext('2d')

canvas.style.width = 300 + 'px'
canvas.style.height = 300 + 'px'

canvas.width = 300
canvas.height = 300

ctx.fillRect(10, 10, 50, 50)

canvas에 바로 width와 height 을 지정해 주었더니 네모가 늘어지지 않고 제대로 표시되는 것을 확인할 수 있습니다.

여기서 canvas의 가로 값과 세로값을 100으로 줄여보겠습니다.

const canvas = document.querySelector('canvas')

const ctx = canvas.getContext('2d')

canvas.style.width = 300 + 'px'
canvas.style.height = 300 + 'px'

canvas.width = 100
canvas.height = 100

ctx.fillRect(10, 10, 50, 50)

이 경우 canvas에 그린 도형이 오히려 3배 커지게 됩니다. 

그 이유는 canvas 사이즈가 원래 가로 100 세로 100 사이즈인데 style 값으로 300으로 늘려주어서 canvas안에 그린 네모도 동일하게 3배 더 커졌기 때문입니다.

그래서 canvas의 원래 사이즈와 style로 변환 값이 같도록 변수를 지정해서 설정해 주는 것이 좋습니다.

const canvas = document.querySelector('canvas')

const ctx = canvas.getContext('2d')

const canvasWidth = 300
const canvasHeight = 300

canvas.style.width = canvasWidth + 'px'
canvas.style.height = canvasHeight + 'px'

canvas.width = canvasWidth
canvas.height = canvasHeight

ctx.fillRect(10, 10, 50, 50)

 

이렇게 canvas를 사용해서 웹사이트에 네모를 그리는 방법에 대해서 알아봤습니다.

궁금하거나 잘 안되는 부분이 있으시다면, 아래 댓글로 남겨주세요.

감사합니다.

댓글