HTML canvas fillStyle attribute

Definition and usage

fillStyle The attribute sets or returns the color, gradient, or pattern used to fill the drawing.

Example

Example 1

Define a rectangle filled with blue:

Your browser does not support the canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle = "#0000ff";
ctx.fillRect(20, 20, 150, 100);

Try It Yourself

Tip:More examples are provided at the bottom of the page.

Syntax

context.fillStyle =color|gradient|pattern;

Attribute value

Value Description
color Indicates the drawing fill color CSS color value). Default value is #000000.
gradient Gradient object used for filling the drawing (LinearorRadial)
pattern Pattern object used for filling the drawing

Technical details

Default value: #000000

More examples

Example 2

Define a gradient from top to bottom as the fill style for the rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 0, 170);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);

Try It Yourself

Example 3

Define a gradient from left to right as the fill style for the rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 170, 0);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);

Try It Yourself

Example 4

Define a gradient from black to red to white as the fill style for the rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 170, 0);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(0.5, "red");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);

Try It Yourself

Example 5

Images used:

lamp

Use images to fill the drawing:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("lamp");
var pat=ctx.createPattern(img,"repeat");
ctx.rect(0,0,150,100);
ctx.fillStyle=pat;
ctx.fill();

Try It Yourself

Browser Support

The numbers in the table indicate the first browser version that fully supports this property.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.