Canvas fillStyle Property

Definition and Usage

fillStyle Property setting or returning the color, gradient, or pattern used to fill the painting.

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). The default value is #000000.
gradient The gradient object used to fill the drawing (LinearOrRadial)
pattern The pattern object used to fill 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 an image 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 attribute.

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.