In the previous example, we set the fill colour of the rectangle like this:
context.fillStyle = 'blue';
In fact, using a named colour is just one of three different ways to choose a colour.
HTML canvas recognises the standard colours. These include the obvious colours such as red, green and blue. They also include more exotic names such as tomato, moccasin and burlywood. There are 140 colours altogether, and they are the same set of colours that SVG uses.
If you want to use your own colours, not just the available named colours, you can use the hex format:
context.fillStyle = '#ff8000';
This defines a colour in terms of its red, green and blue components, with two hex digits for each colour ‘#RRGGBB’. In this case:
- The first two digits FF (hex FF = 255 decimal) specify a red value of 255.
- The next two digits 80 (hex 80 = 128 decimal) specify a green value of 128.
- The final 2 digits 00 specify a blue value of 0.
This creates an orange colour.
The third way to specify colour is via RGB values:
context.fillStyle = 'rgb(96, 32, 128)';
In this case the RGB value is specified by the three values in the brackets: decimal red = 96, green = 64, blue = 128 (a purple colour). This is similar to the previous method, but using decimal values. It really depends on which is more convenient.
One extra method is rgba:
context.fillStyle = 'rgba(0, 255, 255, 0.5)';
In this case the fourth value controls the transparency (or Alpha value, whis what the ‘a’ stands for). A value of 1 makes the colour fully opaque (ie a normal colour), a value of 0 makes the colour totally transparent (ie it is invisible). Values between 0 and 1 make the item partly transparent, so you can see the objects behind it.
The colour shown is a cyan colour, but with a transparency of 50% (a = 0.5).
Here is an example showing the different ways to create a colour:
<!DOCTYPE HTML> <html> <head> </head> <body> <canvas id="myCanvas" width="400" height="200"></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.fillStyle = 'blue'; context.fillRect(50, 50, 75, 75); context.fillStyle = '#ff8000'; context.fillRect(150, 50, 75, 75); context.fillStyle = 'rgb(96, 32, 128)'; context.fillRect(250, 50, 75, 75); context.fillStyle = 'rgba(0, 255, 255, 0.5)'; context.fillRect(290, 80, 75, 75); </script> </body> </html>
Here is the result:
Notice that the cyan square is transparent, you can see the purple square behind it.