HTML Canvas Fill and Stroke
Canvas Fill and Stroke
To define fill-color and outline-color for shapes/objects in canvas, we use the following properties:
Property | Description |
---|---|
fillStyle |
Defines the fill-color of the object/shape |
strokeStyle |
Defines the color of the outline of the object/shape |
The fillStyle Property
The fillStyle
property defines the fill-color of the object.
The fillStyle
property value can be a
color (colorname, RGB, HEX, HSL), a gradient or a pattern.
Example
Set the fill-color to "green" and draw a filled rectangle with the
fillRect()
method:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
</script>
Try it Yourself »
The strokeStyle Property
The strokeStyle
property defines the color of the outline.
The strokeStyle
property value can be a
color (colorname, RGB, HEX, HSL), a gradient or a pattern.
Example
Set the outline-color to "blue" and draw an outlined rectangle with the
strokeRect()
method:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
Try it Yourself »
Combining fillStyle and strokeStyle
It is perfectly legal to combine the two rectangles above.
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// the filled rectangle
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
// the outline rectangle
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
Try it Yourself »
fillStyle and strokeStyle with Alpha Channel
You can also add an alpha channel to both the fillStyle
and the strokeStyle
properties to create
opacity.
Example
Set the opacity to 50% for both the fillStyle
and strokeStyle
properties:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// the filled rectangle
ctx.fillStyle = "rgb(0 255 0 / 50%)";
ctx.fillRect(10,10, 100,100);
// the outline rectangle
ctx.strokeStyle = "rgb(0 0 255 / 50%)";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
Try it Yourself »