[JavaScript / Canvas] CanvasRenderingContext2D 알아보기

 

Canvas

HTML에선 Canvas API를 제공하고 있다.

Canvas는 context를 가지며 이는 요소 안에서 픽셀에 접근할 수 있는 방법이라고 보면 된다.

<canvas id="my-house" width="500" height="700"></canvas>

context는 <canvas>와 </canvas> 사이에 있다 생각하면 된다.

이 때, 실질적으로 그림을 그리는 것은 CanvasRenderingContext2D를 통해 할 수 있다.

 

CanvasRenderingContext2D

context를 만드는 방법은 간단하다. context veriable을 만들어주면 된다.

const canvas = document.getElementById('my-house');
const ctx = canvas.getContext('2d');

 

properties

fillStyle

도형 내부의 색, 그래디언트, 패턴 등을 정의한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const gradient = this.ctx.createLinearGradient(10, 10, 100, 100);
gradient.addColorStop(0, "#F2D3DE");
gradient.addColorStop(1, "#83ABE3");
this.ctx.fillStyle = gradient;
this.ctx.fillRect(10, 10, 100, 100);

 

font

font는 현재 텍스트 스타일을 정의하며 CSS와 동일하게 사용한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.font = 'bold 48px serif';
ctx.strokeText('Hello world', 50, 100);

 

globalAlpha

globalAlpha는 아직 캔버스에 그려지지 않은 도형과 이미지에 적용되는 투명도 값이다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.globalAlpha = 0.5;

ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);

ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

 

lineCap

lineCap속성은 선의 끝의 모양을 결정한다. 값은 "butt", "round", "square"가 있다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = 15;
ctx.lineCap = 'round';
ctx.lineTo(100, 100);
ctx.stroke();

 

lineJoin

lineJoin속성은 서로 다른 선이 만나는 경우, 어떻게 연결할지 정의한다. 만약 수평으로 만나거나 길이가 0인 선분에 대해서는 무시된다. 값은 "bevel", "round", "miter"가 있다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.lineWidth = 20;
ctx.lineJoin = 'round';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(190, 100);
ctx.lineTo(280, 20);
ctx.lineTo(280, 150);
ctx.stroke();

 

lineWidth

lineWidth속성은 선의 굵기를 정의한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.lineWidth = 15;

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(130, 130);
ctx.rect(40, 40, 70, 70);
ctx.stroke();

 

shadowBlur

shadowBlur속성은 그림자에 흐림(블러)효과를 적용한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Shadow
ctx.shadowColor = 'red';
ctx.shadowBlur = 15;

// Rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 100);

 

ShadowColor

shadowBlur은 그림자의 색을 정의한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;

// Filled rectangle
ctx.fillRect(20, 20, 100, 100);

// Stroked rectangle
ctx.lineWidth = 6;
ctx.strokeRect(170, 20, 100, 100);

 

shadowOffsetX, shadowOffsetY

shadowOffsetX와 shadowOffsetY는 각각 그림자의 가로, 세로 길이를 정의한다.

 

example

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetY = 25;
ctx.shadowBlur = 10;

// Rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 80);

// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetY = 25;
ctx.shadowBlur = 10;

// Rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 80);

 

strokeStyle

strokeStyle속성은 선의 색, 그래디언트, 패턴을 정의한다.

 

example

const ctx = document.getElementById('canvas').getContext('2d');

for (let i = 0; i < 6; i++) {
  for (let j = 0; j < 6; j++) {
    ctx.strokeStyle = `rgb(
        0,
        ${Math.floor(255 - 42.5 * i)},
        ${Math.floor(255 - 42.5 * j)})`;
    ctx.beginPath();
    ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true);
    ctx.stroke();
  }
}

 

textAlign

textAlign속성은 텍스트의 정렬을 정의한다. 정렬은 fillText()함수의 x값에 영향을 받는다. 

값은 "left", "right", "center", "start", "end"가 있다.

 

example

const canvas = document.getElementById('canvas');
canvas.width = 500;
const ctx = canvas.getContext('2d');
const x = canvas.width / 2;

ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();

ctx.font = '30px serif';

ctx.textAlign = 'left';
ctx.fillText('left-aligned', x, 40);

ctx.textAlign = 'center';
ctx.fillText('center-aligned', x, 85);

ctx.textAlign = 'right';
ctx.fillText('right-aligned', x, 130);

 

textBaseline

textBasline속성은 텍스트의 기준선을 정의한다.

값은 "top", "hanging", "middle", "alphabetic", "ideographic", "bottom"이 있다.

 

 

 

context로 집 모양 만들기

아래의 context를 사용하면 집 모양이 그려진다.

// Set line width
ctx.lineWidth = 10;

// Wall
ctx.strokeRect(75, 140, 150, 110);

// Door
ctx.fillRect(130, 190, 40, 60);

// Roof
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();