
The HTML canvas fillStyle property defines the color, gradient, or pattern used to fill the drawing.
Syntax:
context.fillStyle=color|gradient|pattern;
value: color
Specify a green fill-color for the square:
<!DOCTYPE html>
<html>
<body>
<canvas id="square-1" width="200" height="200" style="border:1px solid #333;">
</canvas>
<script>
var c = document.getElementById("square-1");
var ctx = c.getContext("2d");
ctx.fillStyle = "#2a9d8f";
ctx.fillRect(50, 50, 100, 100);
</script>
</body>
</html>
Output:
value: gradient
Specify a gradient (top to bottom) as the fill style for the square:
<!DOCTYPE html>
<html>
<body>
<canvas id="square-2" width="200" height="200" style="border:1px solid #333;">
</canvas>
<script>
var c = document.getElementById("square-2");
var ctx = c.getContext("2d");
var create_gradient = ctx.createLinearGradient(0, 0, 0, 150);
create_gradient.addColorStop(0, "#2a9d8f");
create_gradient.addColorStop(1, "#264653");
ctx.fillStyle = create_gradient;
ctx.fillRect(50, 50, 100, 100);
</script>
</body>
</html>
Output:
Specify a gradient that goes from red, to orange, to yellow, as the fill style for the square:
<!DOCTYPE html>
<html>
<body>
<canvas id="square-3" width="200" height="200" style="border:1px solid #333;">
</canvas>
<script>
var c = document.getElementById("square-3");
var ctx = c.getContext("2d");
var createGradient = ctx.createLinearGradient(0, 0, 150, 0);
createGradient.addColorStop(0, "#e76f51");
createGradient.addColorStop(0.5, "#f4a261");
createGradient.addColorStop(1, "#e9c46a");
ctx.fillStyle = createGradient;
ctx.fillRect(50, 50, 100, 100);
</script>
</body>
</html>
Output:
To read more about HTML canvas gradients and learn how to create HTML canvas radial-gradient click here.
value: pattern
Use an image to fill the drawing:
<!DOCTYPE html>
<html>
<body>
<p>Image:</p>
<img src="https://lenadesign.org/wp-content/uploads/2021/06/car.png" id="car" width="39" height="33">
<p>Canvas:</p>
<canvas id="myPattern" width="200" height="200" style="border:1px solid #333;">
</canvas>
<br><br>
<button onclick="draw('repeat')">Repeat</button>
<button onclick="draw('no-repeat')">No-repeat</button>
<script>
function draw(direction) {
var c = document.getElementById("myPattern");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var img = document.getElementById("car")
var pat = ctx.createPattern(img, direction);
ctx.rect(0, 0, 200, 200);
ctx.fillStyle = pat;
ctx.fill();
}
</script>
</body>
</html>
Output:
Image:

Canvas:
Enjoy coding!