A Rect class holds the x, y, width, and height of the rectangles. It generates random colors for their fill.
The draw method uses fillRect. In the loop we draw xtot rectangles in x-direction and ytot rectangles in the y-direction. Each rectangle has x,y size (xsize, ysize) and also x,y padding (xpad, ypad). There are x,y offsets (xoff, yoff), and thus the top-left rectangle starts at those coordinates.
let canvas = document.querySelector("#myCanvas");
let context = canvas.getContext("2d");
class Rect {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = "rgb(" + Math.floor(Math.random() * 256) +
"," + Math.floor(Math.random() * 256) +
"," + Math.floor(Math.random() * 256) + ")";
}
draw() {
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.width, this.height);
}
}
let xoff = 10, yoff = 20,
xsize = 45, ysize = 50,
xpad = 5, ypad = 10,
xtot = 5, ytot = 6;
for (let j = 0; j < ytot; j++) {
let y = yoff + j * (ysize + ypad);
for (let i = 0; i < xtot; i++) {
let x = xoff + i * (xsize + xpad);
let rect = new Rect(x, y, xsize, ysize);
rect.draw();
}
}
Output:
No comments:
Post a Comment