๐Ÿ‘€ Canvas cheatsheet (์ž‘์„ฑ์ค‘)

1. Basic

1-1. getContext()

// canvas ์ฐธ์กฐ
const canvas = document.getElementById('canvas')

// CanvasRenderingContext2D ๋ฐ˜ํ™˜
// 2์ฐจ์› ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ ๊ฐ์ฒด
const ctx = canvas.getContext('2d')

// WebGLRenderingContext ๋ฐ˜ํ™˜
// 3์ฐจ์› ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ ๊ฐ์ฒด(v1)
const ctx = canvas.getContext('webgl')

// WebGL2RenderingContext ๋ฐ˜ํ™˜
// 3์ฐจ์› ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ ๊ฐ์ฒด(v2)
const ctx = canvas.getContext('webgl2')

1-2. getImageData()

// ์บ”๋ฒ„์Šค ImageData ๊ฐ์ฒด ๋ฐ˜ํ™˜
const myImageData = ctx.getImageData(left, top, width, height)
ImageData = {
  width,
  height,
  data,
  //int8ClampedArray์‚ฌ์ด์˜ ์ •์ˆ˜ ๊ฐ’์œผ๋กœ RGBA ์ˆœ์„œ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ํฌํ•จํ•˜๋Š” 1 ์ฐจ์› ๋ฐฐ์—ด์„ ํ‘œํ˜„ 0ํ•˜๊ณ  255(ํฌํ•จ).
}

1-3. putImageData()

// ImageData๊ฐ์ฒด์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์บ”๋ฒ„์Šค์— ํŽ˜์ธํŠธ
ctx.putImageData(imageData, 0, 0)

1-3.

2. Store / Reset

2-1. clearRect()

// ์บ”๋ฒ„์Šค๋ฅผ ํˆฌ๋ช… ๊ฒ€์ • (rgba(0,0,0,0))์œผ๋กœ ์„ค์ •
ctx.clearRect(0, 0, x, y)

2-2. save()

// ํ˜„์žฌ ์ƒํƒœ๋ฅผ ์Šคํƒ์œผ๋กœ push
ctx.save()

2-3. restore()

// ์ €์žฅํ•ด๋‘์—ˆ๋˜ ์ƒํƒœ pop
ctx.restore()

3. Move

3-1. beginPath()

// ๊ฒฝ๋กœ ๋ชฉ๋ก์„ ๋น„์›Œ์„œ ์ƒˆ ๊ฒฝ๋กœ๋ฅผ ์‹œ์ž‘
ctx.beginPath()

3-2. moveTo()

// ๊ฒฝ๋กœ ์ด๋™
ctx.moveTo(x, y)

4. Draw

4-1. lineTo()

// ํ˜„์žฌ ๊ฒฝ๋กœ๋ฅผ ์ž‡๋Š” ์ง์„  ์ƒ์„ฑ
ctx.lineTo(x, y)

4-2. arc()

// ํ˜ธ ์ƒ์„ฑ
ctx.arc(x, y, radius, startAngle, endAngle, false) // ์‹œ๊ณ„
ctx.arc(x, y, radius, startAngle, endAngle, true) // ๋ฐ˜์‹œ๊ณ„

5. Render

5-1. lineTo()

// ํ˜„์žฌ ๊ฒฝ๋กœ๋ฅผ ์ž‡๋Š” ์ง์„  ์ƒ์„ฑ
ctx.lineTo(x, y)

Written by@taenyKim
์›น ํ”„๋ก ํŠธ์—”๋“œ ๊ณต๋ถ€ ๋ธ”๋กœ๊ทธ / Learn in Public

GitHubFacebook