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:
JavaScript:
var c = document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle = "#0000ff"; ctx.fillRect(20, 20, 150, 100);
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:
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);
Example 3
Define a gradient from left to right as the fill style for the rectangle:
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);
Example 4
Define a gradient from black to red to white as the fill style for the rectangle:
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);
Example 5
Images used:

Use images to fill the drawing:
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();
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.