context.fillStyle

Overview

Overviewvisual1

To draw on a canvas, we program the canvas's context to draw lines and shapes on the canvas for us. The color, gradient, or pattern the context will use to fill in a shape is stored in the context.fillStyle property.

We set the context's fillStyle by assigning it a color, gradient, or pattern:

context.fillStyle = color;
context.fillStyle = gradient;
context.fillStyle = pattern;

Any new shape the context fills will be filled using that color, gradient, or pattern. However, assigning a new fillStyle does not affect anything already drawn on the canvas.

Set the Context's FillStyle Property to a Color

It's important to note that context.fillStyle is a property and not a method. A method is a function we use to program the context to do something. For example, we program the context to draw a filled rectangle using the context.fillRect() method.

When assigning a new color to the context.fillStyle property, we assign the color manually ourselves. We are not programming the context to set the color for us.

The context defines colors using CSS color values, which are stored as text strings. In CSS, there are several different ways to describe a color:

  • Color Names
    Certain specific colors have names that all web browsers can identify. For example, the context knows that context.fillStyle = 'DarkOrchid' really means context.fillStyle = '#9932CC'. Here is a full list of HTML5 color names.
  • Hex Triplets
    Colors can also be described using a hex triplet. The color '#9932CC' is actually three separate numbers written in base-16. The first number (99) is the amount of red in the color; the second number (32) is the amount of green; and the third number (CC) is the amount of blue. The value for each color component (red, green, and blue) can range from 00 (none) to FF (maximum). For example, the color red is '#FF0000', which is maximum red, no green, and no blue. Here is a list of common hex triplets.
  • RGB Values
    Instead of describing colors in base-16, colors can also be described using RGB values, which are in base-10. To describe a color using RGB values, we use a text string in the format: 'rgb(red, green, blue)'. Since the numbers 99, 32, and CC in base-16 are equal to 153, 50, and 204 in base-10, '#9932CC' and 'rgb(153, 50, 204)' both describe the same color. RGB values must be whole numbers, and they range from 0-255. To find RGB values for different colors, you can use this tool: RGB Colors.
  • RGBA Format
    Describing a color using the RGBA format is a way to set the color's alpha value, which is its degree of transparency. Alpha values range from 0-1, where 0 is fully transparent and 1 is fully opaque. To set the context's fillStyle to a dark orchid color that is 50% transparent, we would use the text string 'rgba(153, 50, 204, 0.5)', where the first three numbers are RGB values and the fourth number is the alpha value.

In this example, we draw four filled rectangles using four different colors.

Change the names, hex values, RGB values, and alpha values of the colors to see what happens. Change the coordinates of the fourth rectangle to see what happens when it covers one of the other rectangles.

To learn more about the coordinate system and drawing rectangles, visit the Coordinates and fillRect() lessons.

Quick Reference: Coordinates fillRect()

Editor (write code below)
var canvas = document.getElementById('fill_style_example1'); var context = canvas.getContext('2d'); context.fillStyle = 'CornflowerBlue'; context.fillRect(20, 20, 200, 100); // First rectangle context.fillStyle = '#9932CC'; context.fillRect(80, 80, 200, 100); // Second rectangle context.fillStyle = 'rgb(255, 0, 0)'; context.fillRect(140, 140, 200, 100); // Third rectangle context.fillStyle = 'rgba(153, 50, 204, 0.5)'; context.fillRect(200, 200, 200, 100); // Fourth rectangle
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 1

Challenge1visual1
What your drawing should look like

Fill the rectangle at (100, 50) with a width of 200 and a height of 150 using the color named OrangeRed.

Editor (write code below)
var canvas = document.getElementById('fill_style_challenge1'); var context = canvas.getContext('2d'); // ASSIGN THE FILLSTYLE COLOR HERE context.fillRect(100, 50, 200, 150);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge1

Challenge 2

Challenge2visual1
What your drawing should look like

Fill the rectangle at (20, 160) with a width of 260 and a height of 140 using the color with hex values 7B, 68, and EE.

Fill the rectangle at (140, 40) with a width of 200 and a height of 200 using the color with RGB values 46, 139, and 87, and alpha value 0.4.

Editor (write code below)
var canvas = document.getElementById('fill_style_challenge2'); var context = canvas.getContext('2d'); // ASSIGN THE FILLSTYLE COLOR FOR THE FIRST RECTANGLE HERE context.fillRect(20, 160, 260, 140); // ASSIGN THE FILLSTYLE COLOR FOR THE SECOND RECTANGLE HERE context.fillRect(140, 40, 200, 200);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge2

Fill Multiple Shapes with the Same Color

Assigning a color to context.fillStyle sets the color for the context, not a single shape. Any shapes the context fills will be filled with that color until we assign a new fillStyle.

In this example, we draw the flag of the United States of America. We start by setting the fillStyle to 'White' and draw one large white rectangle. Then, we set the fillStyle to '#B22234' and draw seven red stripes on top of the white rectangle. Note that we are only setting the fillStyle once. Finally, we set the fillStyle to '3C3B6E' and draw the blue rectangle in the corner of the flag.

By planning ahead, we only have to draw nine rectangles and set the context.fillStyle property three times. Can you think of a way to draw the flag using only eight rectangles?

Quick Reference: Coordinates fillRect()

Editor (write code below)
var canvas = document.getElementById('fill_style_example2'); var context = canvas.getContext('2d'); context.fillStyle = 'White'; context.fillRect(40, 40, 370, 195); // The white rectangle context.fillStyle = '#B22234'; context.fillRect(40, 40, 370, 15); // The red stripes context.fillRect(40, 70, 370, 15); context.fillRect(40, 100, 370, 15); context.fillRect(40, 130, 370, 15); context.fillRect(40, 160, 370, 15); context.fillRect(40, 190, 370, 15); context.fillRect(40, 220, 370, 15); context.fillStyle = '#3C3B6E'; context.fillRect(40, 40, 148, 105); // The blue rectangle
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 3

Challenge3visual1
What your drawing should look like

Rearrange the lines of code below to draw the image to the right.

As long as the code is placed in the correct order, you should not have to type any code yourself. Try to group the rectangles by fillStyle color.

Editor (write code below)
var canvas = document.getElementById('fill_style_challenge3'); var context = canvas.getContext('2d'); // REARRANGE THE LINES OF CODE BELOW TO DRAW THE IMAGE TO THE RIGHT context.fillStyle = 'Gold'; context.fillStyle = 'DarkOrange'; context.fillStyle = 'FireBrick'; context.fillRect(200, 40, 80, 40); context.fillRect(80, 120, 40, 40); context.fillRect(320, 200, 40, 40); context.fillRect(40, 40, 40, 200); context.fillRect(320, 40, 40, 140); context.fillRect(200, 200, 80, 40); context.fillRect(120, 40, 40, 200); context.fillRect(220, 80, 40, 120);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge3

Set the Context's FillStyle Property to a Gradient

Besides colors, we can also assign a gradient to the context.fillStyle property using either the context.createLinearGradient() method or the context.createRadialGradient() method.

In this example, we create a horizontal linear gradient and assign it to the variable gradient using:

var gradient = context.createLinearGradient(50, 0, 350, 0);

This creates a linear gradient between (50, 0) and (350, 0). If we draw a straight line between (50, 0) and (350, 0), we get a horizontal line. To create a vertical linear gradient, use two points that form a vertical line. We can also create linear gradients at an angle.

We then add two color stops. The first color stop sets the color at position 0 (50, 0) to MediumPurple. The second color stop sets the color at position 1 (350, 0) to Black. Any points between (50, 0) and (350, 0) will be filled with a mixture of MediumPurple and Black.

gradient.addColorStop(0, 'MediumPurple');
gradient.addColorStop(1, 'Black');

We can define a linear gradient with more than two color stops by adding additional color stops at positions between 0-1.

Finally, we assign gradient to context.fillStyle and use the context.fillRect() method to draw three filled rectangles.

context.fillStyle = gradient;
context.fillRect(20, 20, 300, 80);
context.fillRect(200, 120, 200, 80);
context.fillRect(80, 220, 200, 80);

It is important to note that the gradient is defined for the context and within the context's coordinate system. A rectangle positioned to the right of (350, 0) and filled with the gradient will be solid black.

To learn more about the coordinate system, variables, and linear gradients, visit the Coordinates, Variables, and createLinearGradient() lessons.

Quick Reference: Coordinates Variables

Editor (write code below)
var canvas = document.getElementById('fill_style_example3'); var context = canvas.getContext('2d'); var gradient = context.createLinearGradient(50, 0, 350, 0); gradient.addColorStop(0, 'MediumPurple'); gradient.addColorStop(1, 'Black'); context.fillStyle = gradient; context.fillRect(20, 20, 300, 80); context.fillRect(200, 120, 200, 80); context.fillRect(80, 220, 200, 80);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Fill Multiple Shapes with the Same Gradient

We can use the fact that a gradient is defined for the context and within the context's coordinate system to create cool effects.

In this example, we create a vertical linear gradient between (0, 200) and (0, 300), with the color 'Yellow' at position 0 and the color 'Red' at position 1. Then we fill a circle and some text with the same gradient.

To make the text stand out, we add a red outline around it using the context.strokeText() method.

To learn more about the coordinate system, variables, drawing text, and linear gradients, visit the Coordinates, Variables, fillText(), strokeText(), and createLinearGradient() lessons.

Quick Reference: Coordinates Variables

Editor (write code below)
var canvas = document.getElementById('fill_style_example4'); var context = canvas.getContext('2d'); var gradient = context.createLinearGradient(0, 200, 0, 300); gradient.addColorStop(0, 'Yellow'); gradient.addColorStop(1, 'Red'); context.fillStyle = gradient; context.beginPath(); context.arc(220, 160, 140, 0, 2 * Math.PI, false); // Draws a circle context.closePath(); context.fill(); // Fills the circle context.font = 'bold 96px Arial'; // Sets the context's font context.textAlign = 'center'; // Sets the context's text alignment context.fillText('SUNRISE', 220, 250); // Fills a text string context.strokeStyle = 'Red'; // Sets the context's strokeStyle context.strokeText('SUNRISE', 220, 250); // Strokes the same text string
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Set the Context's FillStyle Property to a Pattern

Besides colors and gradients, we can also assign a pattern to the context.fillStyle property using the context.createPattern() method.

Example5visual1

In this example, we fill rectangles using a pattern created from the image to the right.

The code for this example is a little complicated because we have to create the image we use for the pattern, and then we have to wait for the image to load before we can use it. Normally, we would load the image before running our program, which would make the code much simpler.

We start by creating our image, assigning it to the variable img, and supplying the URL where the actual image file is located on the web server.

var img = document.createElement('img');
img.src = '/resources/lessons/fill_style/images/example5Pattern1.png';

Once the image loads from the web server, we create a pattern from img and assign the pattern to the variable pattern using:

var pattern = context.createPattern(img, 'repeat');

This creates a repeating pattern that will tile to fill any shape.

Then, we assign pattern to context.fillStyle and use the context.fillRect() method to draw three filled rectangles.

context.fillStyle = pattern;
context.fillRect(20, 20, 300, 80);
context.fillRect(200, 120, 200, 80);
context.fillRect(80, 220, 200, 80);

Once again, it is important to note that the pattern is defined for the context and within the context's coordinate system. This means the pattern image starts tiling from the context's origin, not the top left corner of the rectangle. As you can see, the edge of the pattern does not necessarily line up with the edges of the rectangles.

To learn more about the coordinate system, variables, and patterns, visit the Coordinates, Variables, and createPattern() lessons.

Quick Reference: Coordinates Variables

Editor (write code below)
var canvas = document.getElementById('fill_style_example5'); var context = canvas.getContext('2d'); var img = document.createElement('img'); img.src = '/resources/lessons/fill_style/images/example5Pattern1.png'; img.onload = function() { var pattern = context.createPattern(img, 'repeat'); context.fillStyle = pattern; context.fillRect(10, 20, 300, 80); context.fillRect(155, 115, 100, 190); context.fillRect(80, 160, 240, 80); };
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Align Patterns to Rectangles

We can align patterns with rectangles if we position the rectangles using the context.translate() method. By moving the origin of the context, each rectangle can be drawn at (0, 0), so the pattern image starts tiling from the rectangle's top left corner.

context.save();
context.translate(10, 20);
context.fillRect(0, 0, 300, 80);
context.restore();

Now, when two rectangles overlap, their patterns don't necessarily overlap because those patterns were drawn using two different coordinate systems.

To learn more about the coordinate system, saving and restoring the drawing state, and translating the coordinate system, visit the Coordinates, save() / restore(), and translate() lessons.

Quick Reference: Coordinates save() / restore() translate()

Editor (write code below)
var canvas = document.getElementById('fill_style_example6'); var context = canvas.getContext('2d'); var img = document.createElement('img'); img.src = '/resources/lessons/fill_style/images/example5Pattern1.png'; img.onload = function() { var pattern = context.createPattern(img, 'repeat'); context.fillStyle = pattern; context.save(); context.translate(10, 20); context.fillRect(0, 0, 300, 80); context.restore(); context.save(); context.translate(155, 115); context.fillRect(0, 0, 100, 190); context.restore(); context.save(); context.translate(80, 160); context.fillRect(0, 0, 240, 80); context.restore(); };
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Ready for the next lesson?

Next up, the "save() / restore()" lesson >