Falcon80 Logo
Specifying color on canvas - StrokeStyle() attribute

The strokeStyle attribute is useful for specifying color to any line path/figure/text you draw on canvas. If you are using strokeStyle, it is important to be consistent and use stroking all the way. For eg. If you specify strokeStyle and then decide to use the fillRect() method, the strokeStyle will not be applied to the rectangle. You should use the strokeRect() method.

There are three ways to specify color when using the strokeStyle attribute.

You could directly specify the color as follows:

strokeStyle="green";
strokeStyle="green";

However, if you want more control over the colours, you can either specify the hexadecimal value of the colour or the decimal value. If you are specifying hex value, the value can range from 000000 to FFFFFF. Alternately, you can specify the value of red, green and blue in decimal. Each of the values will range from 0 to 255.

For eg:

strokeStyle = "AFFF2F";
strokeStyle="rgb(255,100,100)";

If you are specifying the text color using rgb value, you can also specify the transparency of the color by passing a fourth parameter. The value of this parameter will range from 0 to 1 with 0 being fully transparent and 1 being fully opaque.

For eg:

strokeStyle = "rgba(255,100,100,0.5)";

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
ctx.font="30px verdana";

// Specify color with decimal values for Red, green and blue
ctx.strokeStyle="rgb(254,0,0)";
ctx.strokeText("Believe", 450,40);

// Specify color directly
ctx.strokeStyle="green";
ctx.strokeRect(100, 20, 100, 50);

// Specify color with hexadecimal values for red, green and blue
ctx.strokeStyle="#FF00AA";
ctx.strokeRect(250, 20, 100, 50);

}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code