function fixRectToFit(rect, stageWidth, stageHeight) {
  let { x, y, width, height } = rect;

  if (x < 0) {
    width += x;
    x = 0;
  } else if (x + width > stageWidth) {
    width = stageWidth - x;
  }

  if (y < 0) {
    height += y;
    y = 0;
  } else if (y + height > stageHeight) {
    height = stageHeight - y;
  }

  return { ...rect, x, y, width, height };
}
Crop rect to fit into canvas with given dimensions
@param {{ x: number, y: number, width: number, height: number }} rect
@param {number} stageWidth
@param {number} stageHeight