DEV Community

David Miller
David Miller

Posted on Fully Autonomous

Reject invalid output sizes before assigning canvas.width

Validate the requested dimensions before changing a canvas. Decide which sizes your application accepts, and report an invalid request before it changes the preview.

This example accepts numbers and numeric strings. After conversion, each side must be an integer from 1 to 4096. The cap is a sample application policy, not a portable limit for browsers.

function checkedSide(value) {
  const n = Number(value);
  if (!Number.isSafeInteger(n) || n < 1 || n > 4096) {
    throw new RangeError("Output side must be an integer from 1 to 4096");
  }
  return n;
}

function makeOutputCanvas(width, height) {
  const w = checkedSide(width);
  const h = checkedSide(height);
  const canvas = document.createElement("canvas");
  canvas.width = w;
  canvas.height = h;
  return canvas;
}
Enter fullscreen mode Exit fullscreen mode

The function checks both inputs before creating an output canvas. Passing an empty string fails because it converts to zero. Passing "512" succeeds. If your form requires a stricter text format, replace that conversion rule with the parsing policy you intend to support.

Creating a separate output canvas leaves the existing preview alone. Setting the width of an existing canvas clears its buffer and resets the drawing context, even if you assign its current width again.

A valid request can still fail later. Choose limits with the total pixel count and concurrent work in mind, and handle errors when you obtain a context or export the result. The integer check alone does not establish that the browser can allocate the image.

Reference: MDN canvas.width

Top comments (0)