Canvas
Canvas
Canvas API๋ JavaScript ์ HTML
<canvas>
์๋ฆฌ๋จผํธ๋ฅผ ํตํด ๊ทธ๋ํฝ์ ๊ทธ๋ฆฌ๊ธฐ ์ํ ์๋จ์ ์ ๊ณตํ๋ค.์ ๋๋ฉ์ด์ , ๋ฐ์ดํฐ ์๊ฐํ, ๊ทธ๋ํฝ, ๊ฒ์ ๋ฑ ๋ค์ํ ์๊ฐ์ ์ธํฐ๋ ์ ์ ๊ตฌํํ๋๋ฐ ์ฌ์ฉ๋๋ ๊ฐ๋ ฅํ ๋๊ตฌ
Canvas Size
canvas์ size(width, height)๋
์ธ๋ผ์ธ ์์ฑ
์ผ๋ก ์ง์ ํ ๊ฐ๊ณผcss ์คํ์ผ
๋ก ์ง์ ํ ๊ฐ์ ์๋ก ๋ค๋ฅด๊ฒ ๋์ํ๋ค.
์ธ๋ผ์ธ ์์ฑ
์ธ๋ผ์ธ ์์ฑ์ ์ปจ๋ฒ์ค์ ํด์๋(ํฌํจ๋ ํฝ์ ์)๋ฅผ ์ ์ํ๋ค.
์บ๋ฒ์ค ๊ณ ์ ์ ๋ฌผ๋ฆฌ์ ์ธ ํฌ๊ธฐ
์ง์ ํด์ฃผ์ง ์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ์ 300 x 150
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d'); // canvas 2D ๋ ๋๋ง ์ปจํ
์คํธ
const canvasWidth = 300;
const canvasHeight = 300;
canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';
canvas.width = canvasWidth * 2;
canvas.height = canvasHeight * 2;
DPR (Device Pixel Ratio)
ํ๋์ css ํฝ์ ์ ๊ทธ๋ฆด ๋ ์ฌ์ฉ๋๋ ์ฅ์น์ ํฝ์ ์๋ฅผ ์๋ฏธํ๋ค. DPR์ด ๋์์๋ก ์ ๋ช ํ ํ๋ฉด์ ๋ํ๋ธ๋ค.
const DPR = window.devicePixelRatio;
// ๊ณ ํด์๋ ๋์คํ๋ ์ด ํ๊ฒฝ์์๋ ํฝ์
๋ฐ๋๊ฐ ๋๊ธฐ ๋๋ฌธ์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ค์ ํ ์บ๋ฒ์ค ํฌ๊ธฐ๋ง์ผ๋ก๋ ํ๋ฆฟํด ๋ณด์ผ ์ ์๋ค.
// ์ง์ ๋๋ฅผ ๋ํ๊ธฐ ์ํด ์บ๋ฒ์ค ์์ฒด์ ํฌ๊ธฐ๋ฅผ DPR๊ฐ ๋งํผ ๊ณฑํ๋ค.
canvas.width = canvasWidth * DPR;
canvas.height = canvasHeight * DPR;
ctx.scale(DPR, DPR);// ์บ๋ฒ์ค ์์ ๋ด๋ถ์ ๊ทธ๋ํฝ๋ค ์ญ์ ๋์ผํ๊ฒ ๋ณด์ฌ์ง๊ธฐ ์ํด DPR๊ฐ ๋งํผ ๊ณฑํ๋ค.
์ ๊ทธ๋ฆฌ๊ธฐ
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI / 180 * 360);
ctx.fill(); // ctx.stroke();
ctx.closePath();
beginPath()
path๋ฅผ ๊ทธ๋ฆฌ๊ธฐ ์์ํ๋ค๊ณ ์๋ฆฌ๋ ๋ฉ์๋, ์๋ก์ด path๋ฅผ ๊ทธ๋ฆฌ๊ธฐ ์์ํ๋ฉฐ, ์ด์ path๋ ์ด๊ธฐํ์ํจ๋ค.
closePath()
path์ ์์ ์ง์ ๊ณผ ํ์ฌ ์์น๋ฅผ ์ง์ ์ผ๋ก ์ฐ๊ฒฐํ์ฌ path๋ฅผ ๋ซ๋๋ค.
fill()
ํ์ฌ ์ค์ ๋ path์ ์์ ์ฑ์ด๋ค.
fillStyle โ ์ฑ์ธ ์์์ ์ค์
ctx.fillStyle = 'red'
stroke()
ํ์ฌ ์ค์ ๋ path์ ์ค๊ณฝ์ ์ ๊ทธ๋ฆฐ๋ค.
arc()
์์ ๊ทธ๋ฆฌ๋ ๋ฉ์๋, ์ธ์์ ์ ๋ณด๋ ์๋์ ๊ฐ๋ค.
x: number
โ ์์ํ๋ x ์์นy: number
โ ์์ํ๋ y ์์นradius: number
โ ๋ฐ์ง๋ฆ์ ๊ธธ์ดstartAngle: number
โ ์์ํ๋ ๊ฐ๋endAngle: number
โ ๋๋๋ ๊ฐ๋counterclockwise: boolean | undefined
โ ์๊ณ๋ฐฉํฅ(false, default) or ๋ฐ์๊ณ๋ฐฉํฅ(true)
clearRect(x, y, width, height)
์ง์ ํ ์์ญ์ ์ง์ฐ๋ ๋ฉ์๋
ctx.clearRect(0, 0, canvasWidth, canvasHeight); // ์บ๋ฒ์ค ์ ์ฒด ์์ญ ์ง์ฐ๊ธฐ
Last updated