지 구 여 행
[API/Canvas] 캔버스 크기 설정하기 본문
캔버스 크기 설정하기
캔버스 크기 설정
출력되는 이미지의 크기는 2번의 과정을 통해 설정합니다. ①HTML 또는 Javascript로 가상 캔버스의 크기를 설정하고, ②CSS를 통해 브라우저에 출력되는 이미지의 크기를 설정합니다.
HTML
<body>
<canvas id="canvas" width="300" height="300"></canvas>
</body>
Javascript
const canvas = document.querySelector("#canvas")
canvas.width = 300;
canvas.height = 300;
※ CSS와 달리 HTML/Javascript에서는 사이즈 단위(px)를 표기하지 않습니다.
CSS
canvas {
width: 300px;
height: 300px;
border: 5px solid black;
}
See the Pen Creating a drawing board on browser by cosmosunion (@cosmosunion) on CodePen.
예제 1. 캔버스와 이미지의 상대적 크기에 대한 출력 비교
① 캔버스 크기 = 이미지 크기
See the Pen Untitled by cosmosunion (@cosmosunion) on CodePen.
② 캔버스 크기 < 이미지 크기
See the Pen canvas < image by cosmosunion (@cosmosunion) on CodePen.
③ 캔버스 크기 > 이미지 크기
See the Pen Untitled by cosmosunion (@cosmosunion) on CodePen.
고해상도 이미지 출력하기
HTML 또는 Javascript로 크기를 설정한 것은 '캔버스', CSS를 통해 크기를 설정한 것은 '이미지'로 대체하겠습니다. 일반적으로 고해상도 이미지를 출력하기 위해서 '캔버스' 사이즈를 출력될 '이미지' 사이즈보다 2배 크게 설정하는 방법이 있습니다. 예를 들어, 브라우저에 300x300 사이즈의 이미지를 출력할 경우, 캔버스의 사이즈를 600x600으로 설정합니다. 가로, 세로의 비율이 유지되어야 이미지가 왜곡되지 않습니다. 이와 같은 방법으로 고해상도 이미지를 출력할 경우, 연산해야될 픽셀의 개수가 증가하기 때문에 성능이 떨어진다는 단점이 있습니다.
Javascript
const canvas = document.querySelector("#canvas")
canvas.width = 600;
canvas.height = 600;
CSS
canvas {
width: 300px;
height: 300px;
border: 5px solid black;
}
※ 참고자료
1. MDN web docs : https://developer.mozilla.org/ko/docs/Web/API/Canvas_API
2. 1분코딩 - HTML5 Canvas 캔버스 라이브 강좌 #1 : https://youtu.be/JFQOgt5DMBY
'APIs > Canvas API' 카테고리의 다른 글
[API/Canvas] 기본 사용 방법 (0) | 2022.09.28 |
---|---|
[API/Canvas] Canvas API란 (0) | 2022.09.28 |