Applying styles and colors using canvas
Canvas elements can be used to give colors also in the previous post we discussed various drawing functionalities in a canvas element. In this post, we shall discuss the coloring features in the canvas element.
Colors
There are two properties that canvas element provide us to apply colors to shapes
fillStyle = color
strokeStyle = color
strokeStyle parameter helps in defining the outline color of the shape.
lifestyle parameter helps in coloring inside the shape.
Any CSS color code can be used here.
//these all set the fillStyle to 'orange'
ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "rgb(255,165,0)";
ctx.fillStyle = "rgba(255,165,0,1)";
A fillStyle example
In the following fill style example we can find that two loops run to form a grid of rectangles each grid form s a unique color combination The values of I and J runs to form various color codes .
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i=0;i<6;i++){
for (var j=0;j<6;j++){
ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' +
Math.floor(255-42.5*j) + ',0)';
ctx.fillRect(j*25,i*25,25,25);
}
}
}
A strokeStyle example
This strokestyle example is same as the above but with the difference it shows in the property.
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i=0;i<6;i++){
for (var j=0;j<6;j++){
ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' +
Math.floor(255-42.5*j) + ')';
ctx.beginPath();
ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true);
ctx.stroke();
}
}
}