솔미는 성장중

Canvas 태그를 사용해보자 (1) - 사이즈 조절하기 본문

JavaScript

Canvas 태그를 사용해보자 (1) - 사이즈 조절하기

solming 2023. 12. 5. 12:00
728x90

우선, index.html에 canvas 태그를 하나 만들어준다. (id는 나중에 css를 적용시키기 위해 넣어준거라 일단은 중요하지 X)

전체 코드를 먼저 보여주고, 자세한 설명은 아래에서 확인해주세요.

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link  rel="stylesheet" href="reset.css"/>
  <link  rel="stylesheet" href="main.css"/>
  <script type="module" src="./index.js"></script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>
// index.js

const canvas = document.querySelector("canvas");

const ctx = canvas.getContext("2d"); //그리는 도구
console.log(ctx);
const dpr = window.devicePixelRatio; // dpr이 높을수록 선명한 그래픽 (dpr=1이면 1픽셀그리는데 하나 사용, dpr=2면 1px에 2*2로 구성)

const canvasWidth = 300;
const canvasHeight = 300;

// css 에서 width, height 조절 -> canvas 자체의 가로세로를 후보정 하는 느낌 (ex. 3배 확대..)
canvas.style.width = canvasWidth + "px";
canvas.style.height = canvasHeight + "px";

// canvas 자체의 width, height 조절
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
ctx.scale(dpr, dpr); //dpr이 2이상이면 더 선명하게 보이는 효과 줌.

// 사각형 그리기 (x,y,가로, 세로)
ctx.fillRect(10, 10, 50, 50);

 


 

canvas를 조작하기 위해선 2가지 작업을 먼저 해줘야 한다.

const canvas = document.querySelector("canvas"); // html 요소 갖고오기

const ctx = canvas.getContext("2d"); // 그리는 도구

 

console.log(ctx)를 해보면 사용할 수 있는 다양한 메소드들을 확인할 수 있다!

 

canvas를 사용할 땐 width, height에 대해 조금 주의해야할 것이 있다.

canvas 자체의 사이즈와 css를 통해 적용한 사이즈를 구분지어야 한다 ! ✨ 

 

css를 통해 width, height를 지정하는 것은 후보정하는 느낌이라고 이해하면 된다.

아래처럼 두 경우에서의 width, height를 각각 동일하게 맞춰두고 사용하는 것이 일반적이다!

(dpr은 아래에서 설명)

const canvasWidth = 300;
const canvasHeight = 300;

// canvas 자체의 width, height
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;

// css를 통한 width, height 조절
canvas.style.width = canvasWidth + "px";
canvas.style.height = canvasHeight + "px";

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

canvas 자체의 사이즈와 css를 통한 사이즈를 동일하게 갖고갈 때

const canvasWidth = 300;
const canvasHeight = 300;

// canvas 자체의 width, height -> 기본은 width:300px, height:150px
// canvas.width = canvasWidth * dpr;
// canvas.height = canvasHeight * dpr;

// css를 통한 width, height 조절
canvas.style.width = canvasWidth + "px";
canvas.style.height = canvasHeight + "px";

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

canvas 자체 사이즈는 기본 사이즈인데 css로 세로를 2배 늘린것과 같은 상황

 

이렇게 캔버스 사이즈와 css로 조절한 사이즈가 일치하지 않으면 비율이 이상하게 변할 수 있다.


그렇다면 dpr은 무엇일까!?

 

dpr (device pixel ratio)

: 장치의 물리적 픽셀 밀도와 논리적 픽셀 밀도 간의 비율. 
물리적 픽셀은 화면에 표시되는 반면, 논리적 픽셀은 설정에 따라 각 인치 또는 cm에 들어갈 수 있는 개수를 측정

 

 = 하나의 css 픽셀을 그릴 때 사용되는 장치의 픽셀 수

 

 

dpr=1 이라면 1px을 그릴 때 장치에서도 1px을 사용

dpr=2 라면 1px을 그릴 때 장치에선 2px*2px을 사용!

따라서 dpr이 높을수록 선명한 그래픽이 나타난다.

 

 

맥 사용자의 경우 dpr=2이지만, 1인 경우가 보통 대다수. 

자신의 컴퓨터에서 dpr을 알려면 아래 코드를 작성해보자!

const dpr = window.devicePixelRatio;
console.log(dpr)

 

dpr을 구한 이유는 이를 canvas 사이즈에 곱해주어 더욱 선명한 화면을 보이게 하기 위해서이다! (dpr=1이라면 무관함)

canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
ctx.scale(dpr,dpr);

 

선명하게 보이는 원리

1번                                                                                                                           2번

 

3번                                                                                                                           4번

 

728x90