HTML5 Tutorial – Applying Colors and Style in Canvas

In the last three parts of this HTML5 tutorial, we have already discussed the concept and basics of the HTML5 canvas. If you have followed it correctly, now you can easily create basic shapes like rectangles, lines and circles. You have a good idea about the canvas path and know how to draw arcs and curves. In case, you have come straight to this chapter, I will assume you already know these or recommend you to first go through the previous three parts of this tutorial i.e. basics, shapes and paths.

In this part, we are going to add colors to our canvas. Right, we will learn to style the elements. So, get creative and let’s explore the options we have to make our drawings more pretty.

Colors in HTML5 canvas

I am sure; you have got bored seeing the same black color in all our drawings. This is because by default, both fill color and stroke color in canvas is black. We need to define the color we wish to have in our shapes and drawing. Doing this is not a rocket science; it’s just one line of code!

fillStyle = color

strokeStyle = color

I am sure you know what will ‘fillStyle’ and ‘strokeStyle’ properties do. So let’s move on to the color. The color here can be a solid color, a gradient or a pattern. And for solid color, you can use the format just like CSS. See below the examples:

ctx.fillStyle = “red”;

ctx.fillStyle = “#FF0000”;

ctx.fillStyle = “rgb(255,0,0)”;

ctx.fillStyle = “rgba(255,0,0,1)”;

The formats are exactly the same. You can define the fillStyle with the color name, a hex value, in rgb or in rgba. Though you can even use the hsl and rgb in percentage to define the colors like hsl(80%, 20%, 0%) and rgb(100%, 0%, 0%); these are not supported by all web browsers. So, it is good to stick with the earlier ones which we are already using in CSS.

So, let’s quickly create a circle filled with color.

ctx.fillStyle = "#FF0000";
ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);
And what about creating a blue border around this circle?
ctx.fillStyle = "#FF0000";
ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);
ctx.strokeStyle = "#0000FF";
ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);


You should note one important thing here – once you set the fillStyle or strokeStyle property, it becomes a default value and gets automatically applied to all the shapes you draw after that. So, every time you wish to use different color for a shape; you need to reassign the fillStyle or strokeStyle property for that shape. Not a big deal though!

And as you have seen in the example above, you can apply both fillStyle and strokeStyle properties to the same shape. And next time, if you wish to have same fill and stroke colors for other shapes, you don’t need to reassign these again. And you are free to use fillStyle and strokeStyle properties to all the shapes you have already learnt to create – be it a rectangle, a line, a circle, an arc or a curve.

An example of fillStyle property

Here, I am using two for loops to create an array of circles each with a different fill color. It should not be a difficult task for you to understand if you know a little bit programming.

<script type="application/javascript">
function drawShape() {
  var ctx = document.getElementById('canvas').getContext('2d');
  for (var i=0;i<12;i++){
    for (var j=0;j<12;j++){
      ctx.fillStyle = 'rgb(' + Math.floor(255-20*i) + ',' + Math.floor(255-20*j) + ','  + Math.floor(255-10*i) + ')';
<style type="text/css">
border: 1px solid #000000;
<body onload="drawShape();">
<canvas id="canvas" width="300" height="300">
"Sorry, your browser does not support canvas!"


Looks great! Let’s move on to use Gradients.

Gradients in HTML5 canvas

With HTML5 canvas, you are not just limited to using solid colors. You can use both linear and radial gradients as fill and stroke colors for all your shapes. Sounds good? Let’s first have a look at the syntax.



Here, for creating a linear gradient, we require the following arguments:

x1, y1: Co-ordinates of the starting point

x2, y2: Co-ordinates of the end point

For radial gradient, the arguments are a little bit different. Here, we necessarily are defining two circles – starting circle and end circle.

x1, y1, r1: Co-ordinates and radius of the starting circle

x2, y2, r2: Co-ordinates and radius of the end circle

Not a big deal here. For creating gradients, first we define a canvas gradient object like this:

var linearGrad = ctx.createLinearGradient(0,0,200,0);

After this, we can assign the colors by adding color stops with addColorStop method. As you know, there must be at least two color stops for creating a gradient. Of course, you are free to add as many as you wish depending on your requirement.

The addColorStop method takes two arguments – position and color.

addColorStop(position, color)

The position is defined between 0 and 1 which is nothing but the relative position of this color in gradient.  For color argument, you can provide any string which represents a CSS color (like color name, hex value, rgb value, etc.)

Let’s quickly create a simple rectangle filled with a gradient.

            // Define gradient object
            var grd = ctx.createLinearGradient(0, 0, 200, 0);
            grd.addColorStop(0, "#FFFFFF");
            grd.addColorStop(1, "#000000");

            // Fill with gradient
            ctx.fillStyle = grd;
            ctx.fillRect(10, 10, 250, 100);

linear gradient

As you see, I have defined the gradient stops at 0 and 1 (i.e. starting and end point) with white and black color. Nothing very special here – define the gradient, add the color stops, define the fillStyle value as this gradient and create your shape.

Similarly, we can also create a radial gradient.

var grd = ctx.createRadialGradient(150, 150, 20, 150, 150, 200);
grd.addColorStop(0, "#FFFFFF");           
grd.addColorStop(1, "#000000");
ctx.fillStyle = grd;
ctx.arc(150, 150, 100, 0, Math.PI * 2, false);

radial gradient

Canvas Gradient Example

Now, as we already know how to create a linear and a radial gradient, let’s use our skill to create a pretty drawing. In this example, we will use both linear and radial gradients.

function drawShape() {
            var ctx = document.getElementById('canvas').getContext('2d');

            // Define linear gradient object
            var lingrad = ctx.createLinearGradient(0, 0, 0, 400);
            lingrad.addColorStop(0, "#00ABEB");
            lingrad.addColorStop(0.6, "#FFFFFF");
            lingrad.addColorStop(0.6, "#009D00");
            lingrad.addColorStop(1, "#FFFFFF");

            // Define radial gradient object
            var radgrad = ctx.createRadialGradient(300, 100, 20, 300, 100, 120)
            radgrad.addColorStop(0, "#FFFFFF");
            radgrad.addColorStop(0.2, "#FFFF00");
            radgrad.addColorStop(1, "rgba(255, 255, 255, 0.1)");

            //Applying styles
            ctx.fillStyle = lingrad;
            ctx.fillRect(10, 10, 380, 380);

            ctx.fillStyle = radgrad;
            ctx.fillRect(10, 10, 380, 380);

canvas gradient example

In the canvas example above, I have used two gradients – one of each linear and radial. In linear gradient, there are total four color stops which create the sky and the landscape. The radial gradient has three color stops which are used for creating the sun.

Did you notice that we used the transparency in the third color stop of radial gradient? The transparency combined with gradients can do wonders in the drawing. Let’s discuss a little about transparency now.

Transparency in Canvas

Transparency in canvas can be created easily with two methods. In the first method (which we have just used above); we define the transparency with rgba. As you know, with rgba() we can define the color as well as transparency as a CSS3 color value. The rgba() function is very similar to rgb() with one extra parameter. The ‘a’ in rgba denotes alpa which can be set between 0 and 1 – 0 being fully transparent and 1 fully opaque.

In the second method, we can use globalAlpa property of canvas to set the transparency.

globalAlpha = transparency value (between 0 and 1)

Similar to rgba(), the globalAlpha value range is from 0 (fully transparent) to 1(fully opaque).

In most of the cases, you would like to use the first method as it gives you more flexibility. But in case, you want to set the uniform transparency to all your shapes, you should go with the second method.

Patterns in HTML5 Canvas

Just like solid color and gradients, we also have the option to use patterns as fill and stroke color. The createPattern method takes the following parameters:

createPattern(image, type)

Image is a reference to an Image object and the ‘type’ must be a string containing one of the following values: repeat, repeat-x, repeat-y and no-repeat. It is same what you already use in CSS to create a pattern in background. The image can also be a reference to any other canvas element.

Creating pattern in canvas is very similar to creating a gradient. Here also, first we define the pattern and then pass it with a fill or stroke properties. However, in pattern, you must define the image object in advance. That is the image must get loaded before the pattern starts.

var img = new Image();
img.src = 'sample-image.png';
var ptn = ctx.createPattern(img,'repeat');

Canvas Pattern Example

This is a basic example of how we can use pattern in canvas.

function drawShape() {
            var ctx = document.getElementById('canvas').getContext('2d');
            // create new image object to use as pattern
            var img = new Image();
            img.src = 'pattern.jpg';
            img.onload = function () {
                // create pattern
                var ptn = ctx.createPattern(img, 'repeat');
                ctx.fillStyle = ptn;
                ctx.fillRect(10, 10, 380, 280);


As you can see, it is almost similar to the gradient, but you must note one important thing here. We are using onLoad handler in image object to ensure that the image is loaded before it is getting assigned to the pattern.

Line Width

We have played enough with colors, transparency, gradients and patterns. Let’s discuss something else now – how about changing the line width?

By default, lines are very thin. But with lineWidth property, we can change this default setting. The lineWidth property defines the thickness of the current line. It takes the value in pixels; by default it is 1. And needless to say, it takes only positive values.

Let’s see the effect of changing the line width with following example:

function drawShape() {
            var ctx = document.getElementById('canvas').getContext('2d');
            for (var i = 0; i &lt; 10; i++) {
                ctx.lineWidth = 1 + i;
                ctx.moveTo(20, 20 + i * 20);
                ctx.lineTo(250, 20 + i * 20);


Canvas Shadow

The last style we are going to discuss here is the Canvas Shadow. With Shadow, you can create shadow to any shape inside the canvas element. It takes the following four properties:

shadowOffsetX = float

shadowOffsetY = float

shadowBlur = float

shadowColor = color

It is very similar to the CSS3 box-shadow property. shadowOffsetX and shadowOffsetY are the values in pixels which indicate the distance of the shadow in X and Y direction. For positive values of X and Y offset; the shadow is extended right and down respectively. If you use negative values here, it will get extended in left and up direction.

shadowBlur defines the blur effect. By default, this value is zero making the shadow fully sharp. As you increase the value, the shadow becomes more blur.

You can define the color value in any valid CSS3 color value format. By default, it is black and fully transparent. If you don’t define any color, you won’t see any shadow. And as discussed above, if you use rgba() to define the shadow color, you can introduce transparency also.

function drawShape() {
            var ctx = document.getElementById('canvas').getContext('2d');
            ctx.shadowOffsetX = 5;
            ctx.shadowOffsetY = 5;
            ctx.shadowBlur = 2;
            ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
            ctx.fillRect(20, 20, 200, 200);

canvas shadow

This is all about styles in HTML5 Canvas.  In the next section; we will learn to draw and style text in canvas.

>> Font and Text in Canvas

Leave a Reply

Your email address will not be published. Required fields are marked *