Frontend/Canvas

[Canvas] 캔버스 사용하기 | 캔버스 사이즈 | fillRect()

gamzaggang7 2024. 4. 14. 22:52
728x90

캔버스를 사용하기 위해 index.html을 생성하고 body 태그 안에 canvas 태그를 넣는다. 화면은 전체화면으로 바꾸고 캔버스에 색상을 넣었다. index.js를 모듈 타입으로 불러온다.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.9/dat.gui.min.js" integrity="sha512-WoO4Ih0CDOSLYafy22wZD/mcJ7k0ESLqtQsFa6zFKnEUrbtuGU+GkLtVhgt93xa2qewG5gKEC6CWlN8OaCTSVg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <title>Canvas Particle</title>
    <style>
        html,
        body {
            margin: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        canvas {
            background-color: red;
        }
    </style>
</head>

<body>
    <canvas></canvas>
    <script type="module" src="./index.js"></script>
</body>

</html>

 

index.js에 canvas를 불러오고 콘솔로 찍어 잘 불러졌는지 확인한다.

const canvas = document.querySelector('canvas')
console.log(canvas);
728x90

이때 캔버스의 기본 사이즈가 300*150인걸 확인할 수 있다.

 

캔버스에 어떤 것을 그리려면 도구가 필요하다. getContext메서드로 2d 도구를 불러와 ctx라는 변수에 담는다.

const ctx = canvas.getContext('2d')
console.log(ctx);

ctx를 콘솔로 찍어 확인해 보면 다양하게 쓸 수 있는 메서드들이 저장되어있다.

여기서 조금 더 내려보면 fillRect라는 메서드가 있는데 이걸 이용해서 사각형을 그려보겠다. fillRect의 파라미터는 순서대로 시작점 x, 시작점 y, 가로길이, 세로길이다. (10, 10) 지점에 50*50 사이즈의 사각형을 그린다.

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

 

 

캔버스의 사이즈는 css로 직접 수정할 수도 있고, 캔버스 자체의 속성은 width와 height를 조절할 수도 있다. js 파일에서 css의 width와 height를 300px로 조절한다.

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

원래의 캔버스 사이즈인 300*150에서 css로 강제로 300*300으로 늘려 캔버스 안의 정사각형이 직사각형이 되었다. 이번엔 캔버스 자체의 가로 세로 길이를 300으로 맞춰준다.

canvas.width = 300
canvas.height = 300

정사각형은 원래의 크기를 잘 유지한 채 캔버스의 크기만 바꼈다. 캔버스의 가로세로 길이를 100으로 바꿔보자.

canvas.width = 100
canvas.height = 100

정사각형이 조금 흐릿하게 보인다. 캔버스 자체의 크기가 100*100인데 css의 크기에 맞춰 3배 확대 되었기 때문에 픽셀이 깨진 것이다. 그래서 캔버스 작업을 할 때는 style의 캔버스 element 사이즈와 캔버스 자체의 사이즈를 똑같이 맞춰서 작업해야 한다. 이를 편하게 관리하기 위해 캔버스의 가로 세로를 따로 정의한다.

const canvasWidth = 300
const canvasHeight = 300

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

canvas.width = canvasWidth
canvas.height = canvasHeight
728x90