⊗jsSpCnvLC 265 of 281 menu

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:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let 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:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let 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

enru