In this article we will see how to draw a line in a Loop or cycle in HTML5; specifically, with the Canvas API; Although the Canvas API already offers primitives to draw a line (lineTo()), in this exercise we will paint a line from squares; of variable sizes, which will be the "pixels" that make up our line; To draw a square we will use the following function:
ctx.fillRect(X,Y,Width,Height);
X: The X coordinate of the top left corner of the rectangle.
Y: The Y coordinate of the top left corner of the rectangle.
Width: Width of the rectangle in pixels.
Height: Length of the rectangle in pixels.
Drawing the line with the Canvas API
We define the size of the Canvas in pixels; the Canvas is going to be a square:
var tamCanvas = 360;
The next thing is to define how many "pixels" the line will consist of and their size:
var numCuadrados = 10;
var tam = 100;
Now we need to define the spacing between the "pixels"; which will be smaller as we increase the number of rectangles:
var espaciado = (tamCanvas-tam)/(numCuadrados-1);
Now we perform a cycle where we will draw the "pixels" that will make up the line:
for(var i=0; i <numCuadrados; i++){
ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.fillRect(i*espaciado, i*espaciado, tam, tam);
}
Final score
Interactive example
If you have doubts about the operation of the previous parameters, in this example you can vary the value of each parameter:
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter