/Canvas_Rect

Primary LanguageJavaScript

๐Ÿ›  ๊ธฐ๋Šฅ ์‹œ์—ฐ 



๐Ÿ”ฅ HTMLCanvasElement.getContext()


  • HTMLCanvasElement.getContext() ๋ฉ”์†Œ๋“œ๋Š” ์บ”๋ฒ„์Šค์˜ ๋“œ๋กœ์ž‰ ์ปจํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜

var ctx = canvas.getContext(contextType);
var ctx = canvas.getContext(contextType, contextAttributes);
  • ๐Ÿ‘‰ contextType ์บ”๋ฒ„์Šค์— ์—ฐ๊ด€๋œ ๋“œ๋กœ์ž‰ ์ปจํ…์ŠคํŠธ๋ฅผ ์ •์˜ํ•˜๋Š” ์ปจํ…์ŠคํŠธ ์‹๋ณ„์ž๋ฅผ ๊ฐ–๋Š” DOMString์ž…๋‹ˆ๋‹ค. ๊ฐ€๋Šฅํ•œ ๊ฐ’์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

    • "2d", 2์ฐจ์› ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” CanvasRenderingContext2D (en-US) ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค.


  • ๐Ÿ‘‰ contextAttributes ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋ช‡ ๊ฐ€์ง€ ์ปจํ…์ŠคํŠธ ์†์„ฑ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


๐Ÿ”ฅ ์บ”๋ฒ„์Šค(canvas)๋ฅผ ์ด์šฉํ•œ ๋„ํ˜• ๊ทธ๋ฆฌ๊ธฐ


fillRect(x, y, width, height)
์ƒ‰์น ๋œ ์ง์‚ฌ๊ฐํ˜•์„ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค.

strokeRect(x, y, width, height)
์ง์‚ฌ๊ฐํ˜• ์œค๊ณฝ์„ ์„ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค.

clearRect(x, y, width, height)
ํŠน์ • ๋ถ€๋ถ„์„ ์ง€์šฐ๋Š” ์ง์‚ฌ๊ฐํ˜•์ด๋ฉฐ, ์ด ์ง€์›Œ์ง„ ๋ถ€๋ถ„์€ ์™„์ „ํžˆ ํˆฌ๋ช…ํ•ด์ง‘๋‹ˆ๋‹ค.

  • ๐Ÿ‘‰ ์ง์‚ฌ๊ฐํ˜• ๋„ํ˜• ์˜ˆ์ œ
function draw() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");

    ctx.fillRect(25, 25, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);
  }
}

๐Ÿ”ฅ ์Šคํƒ€์ผ๊ณผ ์ƒ‰ ์ ์šฉํ•˜๊ธฐ


  • ๐Ÿ‘‰ ๋„ํ˜•์— ์ƒ‰์„ ์ ์šฉํ•˜๊ณ ์ž ํ•˜๋ฉด, fillStyle๊ณผ strokeStyle ๋‘ ๊ฐ€์ง€ ์ค‘์š”ํ•œ ์†์„ฑ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

fillStyle = color

๋„ํ˜•์„ ์ฑ„์šฐ๋Š” ์ƒ‰์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

strokeStyle = color

๋„ํ˜•์˜ ์œค๊ณฝ์„  ์ƒ‰์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ”ฅ ํ…์ŠคํŠธ ๊ทธ๋ฆฌ๊ธฐ


  • ๐Ÿ‘‰ ์บ”๋ฒ„์Šค ๋ Œ๋”๋ง ์ปจํ…์ŠคํŠธ(canvas rendering context)๋Š” ํ…์ŠคํŠธ๋ฅผ ๋ Œ๋”๋งํ•˜๋Š” ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์ œ๊ณต

fillText(text, x, y [, maxWidth])

์ฃผ์–ด์ง„ (x, y) ์œ„์น˜์— ์ฃผ์–ด์ง„ ํ…์ŠคํŠธ๋ฅผ ์ฑ„์›๋‹ˆ๋‹ค. ์ตœ๋Œ€ ํญ(width)์€ ์˜ต์…˜ ๊ฐ’ ์ž…๋‹ˆ๋‹ค.

strokeText(text, x, y [, maxWidth])

์ฃผ์–ด์ง„ (x, y) ์œ„์น˜์— ์ฃผ์–ด์ง„ ํ…์ŠคํŠธ๋ฅผ ์น (stroke)ํ•ฉ๋‹ˆ๋‹ค. ์ตœ๋Œ€ ํญ(width)์€ ์˜ต์…˜ ๊ฐ’ ์ž…๋‹ˆ๋‹ค.

  • ๐Ÿ‘‰ fillText ์˜ˆ์ œ : ํ…์ŠคํŠธ๋Š” ํ˜„์žฌ์˜ fillStyle์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฑ„์›Œ์ง‘๋‹ˆ๋‹ค.
function draw() {
  var ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.fillText("Hello world", 10, 50);
}

  • ๐Ÿ‘‰ strokeText ์˜ˆ์ œ : ํ…์ŠคํŠธ๋Š” ํ˜„์žฌ์˜ strokeStyle์„ ์ด์šฉํ•˜์—ฌ ์ฑ„์›Œ์ง‘๋‹ˆ๋‹ค.
function draw() {
  var ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.strokeText("Hello world", 10, 50);
}