개인 노트 정리) Canvas - 1-02. 캔버스 사이즈 이해하기
인터랙티브 웹 개발 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>Document</title>
<style>
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
canvas {
background-color: orange;
}
</style>
</head>
<body>
<canvas></canvas>
<script type="module" src="./index.js"></script>
</body>
</html>
index.js
const canvas = document.querySelector("canvas");
console.log(canvas);
## 캔버스에 그리기
- 도화지에 무언가를 그리려면 도구가 있어야 합니다.
index.js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');
console.log(ctx);
- 2d 작업을 도와주는 메소드들을 console 출력에서 확인할 수 있습니다.
이제 사각형을 그려보겠습니다.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx);
ctx.fillRect(10, 10, 50, 50); // 시작하는 x값, 시작하는 y값, 가로길이, 세로길이
fillRect는 사각형을 그리는데 도움을 줍니다.
canvas를 기준으로 canvas 안쪽에 가로 10, 세로 10 위치에 가로길이 50, 세로길이 50 인 사각형이 그려졌습니다.
## 캔버스 사이즈에 대한 이해
캔버스의 사이즈를 다루는 방식에는 2가지가 있습니다. 이 두가지 방식을 동시에 다뤄주어야 합니다.
1. css 값을 직접 수정해서 캔버스사이즈를 조절하는 방식.
2. 캔버스 자체의 속성인 width와 height 값을 조절하는 방식.
먼저 스타일을 css에서 바꿔주어도 되지만, javascript 파일 안에서 width와 height를 300px로 만들어보겠습니다.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx);
canvas.style.width = 300 + "px";
canvas.style.height = 300 + "px";
ctx.fillRect(10, 10, 50, 50); // 시작하는 x값, 시작하는 y값, 가로길이, 세로길이
캔버스는 기본크기인 300x150에서 300x300으로 바꼈지만, 안의 사각형은 직사각형이 되어버렸습니다.
이렇게 된 이유는 css에서 정의한 가로 세로 픽셀이 아니라 캔버스 자체에 width height가 기본적으로 300x150으로 설정이 되어있는데, css를 통해서 세로를 강제로 2배 늘렸기 때문입니다.
이 상태에서 canvas 자체의 width와 height도 똑같이 300으로 맞추어주게 되면..
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx);
canvas.style.width = 300 + "px";
canvas.style.height = 300 + "px";
canvas.width = 300;
canvas.height = 300;
ctx.fillRect(10, 10, 50, 50); // 시작하는 x값, 시작하는 y값, 가로길이, 세로길이
이처럼 정상적으로 출력됩니다.
참고로 canvas의 크기를 100x100으로 줄이게 되면..
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx);
canvas.style.width = 300 + "px";
canvas.style.height = 300 + "px";
canvas.width = 100;
canvas.height = 100;
ctx.fillRect(10, 10, 50, 50); // 시작하는 x값, 시작하는 y값, 가로길이, 세로길이
css의 크기에 맞춰서 3배 확대가 되었기 때문에 픽셀이 깨져서 흐릿하게 보이게 됩니다.
그래서 보통 canvas 작업을 할 때는 스타일의 canvas 엘리먼트 사이즈와 canvas 고유의 사이즈를 똑같이 맞춰서 작업을 해주게 됩니다.
아래처럼 변수로 넣어주면 좋습니다.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx);
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); // 시작하는 x값, 시작하는 y값, 가로길이, 세로길이
## window.devicepixelratio
- 줄여서 dpr 라고 부릅니다.
- 하나의 css 픽셀을 그릴 때 사용되는 장치의 픽셀 수라고 합니다.
- 이 윈도우 전역변수 값을 통해서 css 1픽셀을 실제로 그리는데 장치의 몇 픽셀을 쓰는지 알 수 있습니다.
- dpr이 높을 수록 더 선명한 그래픽을 보여줍니다.
- dpr이 2라면 1픽셀을 그리는데 4개의 픽셀을 쓰게 됩니다.
### canvas 사이즈 조절하기
이제 이 dpr 값을 통해서 canvas의 사이즈를 다시 조절해 보겠습니다.
먼저 컴퓨터의 dpr 값을 콘솔로 출력해봅니다.
console.log(window.devicePixelRatio); // 1
아래처럼 dpr을 곱해줍니다.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const dpr = window.devicePixelRatio; // 1. devicePixelRatio 값을 구한 뒤,
const canvasWidth = 300;
const canvasHeight = 300;
canvas.style.width = canvasWidth + "px";
canvas.style.height = canvasHeight + "px";
// 2. dpr 값을 canvas의 width와 height에 곱해줍니다.
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
ctx.scale(dpr, dpr) // 3. 그리려는 객체에도 가로와 세로에 dpr값을 각각 곱해줍니다.
ctx.fillRect(10, 10, 50, 50);
이렇게 해주는 이유는
dpr 값이 1인 경우는 아무런 효과를 볼 수 없지만, dpr이 2 이상인 경우는 좀 더 선명하게 보이게 됩니다.