In the previous article on drawing, only the default color (black) is used when drawing paths and filling paths. ​

If you want to color graphics, there are two important attributes that you can do.

//Sets or returns the color, gradient, or mode used to fill the paint.
//color: indicates the CSS color value for the fill color of the drawing. The default value is × 000000.
//gradient: gradient object (linear or radioactive) used to fill a drawing
//pattern: pattern object used to fill a drawing
context.fillStyle=color|gradient|pattern;

//Sets or returns the color, gradient, or mode used for strokes.
//color: indicates the CSS color value for the fill color of the drawing. The default value is × 000000.
//gradient: gradient object (linear or radioactive) used to fill a drawing
//pattern: pattern object used to fill a drawing
context.strokeStyle=color|gradient|pattern;

//There are many forms of filling with color:

//1. Fill with color string
context.fillStyle = "red";

//2. Fill with hexadecimal digit string
context.fillStyle = "#FF0000";

//3. Fill with hexadecimal digit string shorthand
context.fillStyle = "#F00";

//4. Use RGB color mode to set color
context.fillStyle = "rgb(255,0,0)";

//5. Use RGBA color mode to set the color. It is based on RGB color mode, and has more parameters to control alpha transparency. The value range is from 1 (opaque) to 0 (transparent).
context.fillStyle = "rgba(255,0,0,1)";

//6. Use HSL color mode to set the color, which is a representation of the points in RGB color model in cylindrical coordinate system. HSL is the color representing the three channels of hue (H), saturation (s), and lightness (L).
context.fillStyle = "hsl(0,100%,50%)";

//7. Use HSLA color mode to set the color. It is based on HSL color mode, and has more parameters to control alpha transparency. The value range is from 1 (opaque) to 0 (transparent).
context.fillStyle = "hsla(0,100%,50%,1)";

By default, strokes and fill colors are black. Once the value of strokestyle or fillStyle is set, the new value will become the default value of the new drawing. If we want to give each graphic a different color, we need to reset the value of fillStyle or strokestyle.

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
for (var i = 0; i < 20; i++){
    for (var j = 0; j < 20; j++){
        ctx.fillStyle = 'rgb(' + Math.floor(255 - 225 / 20 * i) + ',' + Math.floor(255 - 225 / 20 * j) + ',0)';
        ctx.fillRect(j * 10, i * 10, 10, 10);
    }
}

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
for (var i = 0; i < 20; i++){
    for (var j = 0; j < 20; j++){
        ctx.strokeStyle = 'rgb(' + Math.floor(255 - 225 / 20 * i) + ',' + Math.floor(255 - 225 / 20 * j) + ',0)';
        ctx.strokeRect(j * 10, i * 10, 10, 10);
    }
}