This Rect class expects i and j grid locations and gets x, y, width, and height of the rectangles using global variables. It generates random colors for their stroke and a light color for the fill.
The draw method uses strokeRect and fillRect. In the loop we draw xtot rectangles in x-direction and ytot rectangles in the y-direction. Now we have simplified the loop and increased complexity of class. Usually this is what you want to do so the main code is less.
// 2. stroke Rectangles
let canvas = document.querySelector("#myCanvas");
let context = canvas.getContext("2d");
let strokeSize = 10;
let xoff = 10, yoff = 20,
xsize = 50, ysize = 50,
xpad = 10, ypad = 10,
xtot = 4, ytot = 3;
class Rect {
constructor(i, j) {
this.x = xoff + i * (xsize + xpad);
this.y = yoff + j * (ysize + ypad);
this.width = xsize;
this.height = ysize;
this.color = "rgb(" + Math.floor(Math.random() * 256) +
"," + Math.floor(Math.random() * 256) +
"," + Math.floor(Math.random() * 256) + ")";
}
draw() {
context.lineWidth = strokeSize;
context.strokeStyle = this.color;
context.strokeRect(this.x, this.y, this.width, this.height);
context.fillStyle = "#EDC";
context.fillRect(this.x, this.y, this.width, this.height);
}
}
for (let j = 0; j < ytot; j++) {
for (let i = 0; i < xtot; i++) {
let rect = new Rect(i, j);
rect.draw();
}
}
Output:
No comments:
Post a Comment