Simple Canvas Drawing Destructured both ways

by Dominic Myers

HTML

<canvas id="canvas" width="500" height="300"></canvas>

CSS

#canvas {
  border: 1px solid black
}

JavaScript

const rectangles = [];
(() => {
  const canvas = document.getElementById("canvas");
  const context = canvas.getContext("2d");
  let x, y, width, height;
  const redraw = (callback) => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    if (rectangles.length) {
      rectangles.forEach((rectangle) => {
        const {x, y, width, height} = rectangle;
        context.fillRect(x, y, width, height);
      })
    }
    if (callback) {
      callback();
    }
  };
  canvas.addEventListener("mousedown", (event) => {
    if (typeof(x) === "undefined" || x === null) {
      x = event.pageX - canvas.offsetLeft;
      y = event.pageY - canvas.offsetTop;
    }
  });
  canvas.addEventListener("mousemove", (event) => {
    if (typeof(x) !== "undefined" && x !== null) {
      width = (event.pageX - canvas.offsetLeft) - x;
      height = (event.pageY - canvas.offsetTop) - y;
      redraw(() => {
        context.fillRect(x, y, width, height);
      });
    }
  });
  canvas.addEventListener("mouseup", (event) => {
    if (typeof(x) !== "undefined" && x !== null) {
      width = (event.pageX - canvas.offsetLeft) - x;
      height = (event.pageY - canvas.offsetTop) - y;
      rectangles.push({
        x,
        y,
        width,
        height
      });
      x = null;
    }
  });
})();