Search⌘ K
AI Features

Colors, strokeStyle, and fillStyle!

Explore how to use fillStyle and strokeStyle properties to add colors and outlines to shapes in HTML5 Canvas. Learn various methods for specifying colors including hex codes, CSS keywords, RGB, RGBA with transparency, and HSL values. Understand how these options allow you to create visually engaging and customizable graphics using JavaScript.

The primary way you colorize content is by setting the strokeStyle property for shape outlines and the fillStyle property for the shape insides:

widget

Between these two properties, you can color everything from lines to geometric shapes to text.

Let's say we have a rectangle that looks as follows:

widget

The code responsible for this work of art looks like this:

To set the fill color of this element, add line 3 that specifies the fillStyle property:

Javascript (babel-node)
context.beginPath();
context.rect(75, 100, 250, 150);
context.fillStyle = "#FFCC00";
context.fill();

Let’s not stop with just the fill. Since we are already here, we are going to next add a thick outline and give that a color via the strokeStyle property. Add lines 10-12 to your code:

The two lines of code that took our pretty drab looking rectangle and helped make it a bit more lively are the fillStyle and strokeStyle properties. You can argue that the fillStyle probably had more to do with it since the outline is still a pretty dull shade of gray, but anyway…but what we are going to do from here on out is take a look at the various ways you have for specifying colors. While I will be focusing only on the ...