JavaScript에서 canvas 선 색상 변경하기

이제 외곽선과 채우기 색상을 변경하는 방법을 배워봅시다. 이를 위한 속성은 다음과 같습니다: 속성 strokeStyle은 외곽선 색상을 설정하고, 속성 fillStyle은 채우기 색상을 설정합니다. 색상은 일반적인 CSS 형식으로 설정됩니다.

예시

rect를 사용하여 외곽선을 그리고 빨간색으로 채워봅시다:

html<canvas width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');

ctx.rect(50, 50, 100, 100);
ctx.strokeStyle = 'red';
ctx.stroke();

Результат:

예시

rect를 사용하여 사각형을 그리고 녹색으로 채워봅시다:

html<canvas width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');

ctx.rect(50, 50, 100, 100);
ctx.fillStyle = 'green';
ctx.fill();

Результат:

주의 사항

중요: strokeStyle나 fillStyle를 설정하면, 새 값은 이 시점부터 그려지는 모든 도형에 적용됩니다. 다른 색상이 필요한 각 도형에 대해 fillStyle 또는 strokeStyle 값을 다시 설정해야 합니다.

실습 문제

Задание 1
Задание 2
Задание 3
Задание 4