DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

JavaScript Quiz - Part 2

Create nested rectangles on a canvas using a loop, so you only need to write the calls to ctx.strokeStyle and ctx.strokeRect once.

Solution

const canvasRects = [
  {
    color: "orange",
    sides: [20, 20, 180, 80],
  },
  {
    color: "red",
    sides: [30, 30, 160, 60],
  },
  {
    color: "green",
    sides: [40, 40, 140, 40],
  },
  {
    color: "blue",
    sides: [50, 50, 120, 20],
  },
];

let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");

for (let rect of canvasRects) {
  let { sides } = rect;
  ctx.strokeWidth = 2;
  ctx.strokeStyle = rect.color;
  ctx.strokeRect(sides[0], sides[1], sides[2], sides[3]);
}
Enter fullscreen mode Exit fullscreen mode

Result

Top comments (0)