Line color change in canvas in JavaScript
Let's now learn how to change a color of
the outline and fill. There are the
following properties for this: the
strokeStyle property sets the
outline color, and the fillStyle
property sets the fill color. Colors are
set in the regular
CSS format.
Example
Let's draw an outline with rect
and color it red:
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();
Результат:
Example
Let's draw a square with
rect and color it green:
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();
Результат:
Comment
Important: when you set strokeStyle
or fillStyle, the new value will
be applied to all shapes drawn from that
point on. For each shape that you need
a different color for, you must overwrite
the fillStyle or strokeStyle
value.
Practical tasks
Задание 1
Задание 2
Задание 3
Задание 4