Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

ctx.filter does nothing in Safari: how to detect it, and a blur fallback that matches CSS blur()

ctx.filter = "blur(12px)" is the shortest way to blur something on a 2D canvas. It works in Chrome and Firefox. In Safari, and so in every browser on an iPhone, it does nothing, and it does nothing quietly: no exception,

ctx.filter = "blur(12px)" is the shortest way to blur something on a 2D canvas. It works in Chrome and Firefox. In Safari, and so in every browser on an iPhone, it does nothing, and it does nothing quietly: no exception, no console warning, and the drawing comes out sharp.

I found this the unpleasant way. A face-blur tool I maintain exported the "blurred" region unblurred on iOS. Every test passed, because every test ran in Chromium. This post is the detection and the fallback I ended up with.

Why there is no error

Safari keeps CanvasRenderingContext2D.filter behind a preference that is off by default (check the compatibility table on MDN for the current state). When the property does not exist, this line is ordinary JavaScript:

ctx.filter = "blur(12px)";

It adds a plain property called filter to the context object. Reading it back returns the string you wrote, so the usual "set it and see whether it stuck" test says yes.

Detect it on the prototype

The property is real only if the prototype has it:

let filterSupport: boolean | undefined;

export function canvasFilterSupported(): boolean {
  if (filterSupport === undefined) {
    filterSupport =
      typeof CanvasRenderingContext2D !== "undefined" &&
      "filter" in CanvasRenderingContext2D.prototype;
  }
  return filterSupport;
}

The fallback: three box blurs

A Gaussian blur can be approximated very closely by running a box blur three times. The widths of the three boxes for a given standard deviation come from Peter Kovesi's "Fast Almost-Gaussian Filtering"; Ivan Kutskir's write-up of it is where most JavaScript versions come from, this one included.

/** Widths of `n` box blurs whose sum approximates a Gaussian of `sigma`. */
export function boxSizesForGauss(sigma: number, n = 3): number[] {
  const wIdeal = Math.sqrt((12 * sigma * sigma) / n + 1);
  let wl = Math.floor(wIdeal);
  if (wl % 2 === 0) wl -= 1;
  const wu = wl + 2;
  const m = Math.round(
    (12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4),
  );
  return Array.from({ length: n }, (_, i) => (i < m ? wl : wu));
}

CSS blur(12px) means a standard deviation of 12 px, so sigma here is the same number you would have put in the filter string.

Each box blur is two passes, one along rows and one along columns, and each pass is a sliding sum: add the pixel entering the window, subtract the one leaving. The cost per pixel does not depend on the radius.

function boxPass(
  src: Uint8ClampedArray,
  dst: Uint8ClampedArray,
  width: number,
  height: number,
  r: number,
  horizontal: boolean,
): void {
  const lines = horizontal ? height : width;
  const len = horizontal ? width : height;
  const step = horizontal ? 4 : width * 4;
  const last = len - 1;
  const inv = 1 / (2 * r + 1);
  for (let line = 0; line < lines; line += 1) {
    const base = horizontal ? line * width * 4 : line * 4;
    for (let c = 0; c < 4; c += 1) {
      const o = base + c;
      let sum = 0;
      for (let i = -r; i <= r; i += 1) {
        sum += src[o + Math.min(last, Math.max(0, i)) * step];
      }
      for (let i = 0; i < len; i += 1) {
        dst[o + i * step] = sum * inv;
        sum +=
          src[o + Math.min(last, i + r + 1) * step] -
          src[o + Math.max(0, i - r) * step];
      }
    }
  }
}

export function gaussianBlurRGBA(
  data: Uint8ClampedArray,
  width: number,
  height: number,
  sigma: number,
): void {
  const tmp = new Uint8ClampedArray(data.length);
  for (const size of boxSizesForGauss(sigma)) {
    const r = (size - 1) / 2;
    if (r < 1) continue;
    boxPass(data, tmp, width, height, r, true);
    boxPass(tmp, data, width, height, r, false);
  }
}

The Math.min / Math.max clamps repeat the edge pixel past the border. That is a deliberate difference from ctx.filter, which blurs in the transparency outside the image and leaves a soft, see-through rim. For a photo you are about to export, a solid edge is the better result.

Blur a smaller copy

A wide blur throws away fine detail, so it does not need full resolution. The fallback shrinks the image by k, blurs with radius / k, and scales back up. k is chosen so the blur on the small copy is still at least 4 px wide; below that the box approximation gets coarse.

export function blurCanvas(source: HTMLCanvasElement, radius: number): HTMLCanvasElement {
  const out = document.createElement("canvas");
  out.width = source.width;
  out.height = source.height;
  const ctx = out.getContext("2d");
  if (!ctx) throw new Error("Canvas 2D context unavailable");
  if (radius <= 0) {
    ctx.drawImage(source, 0, 0);
    return out;
  }
  if (canvasFilterSupported()) {
    ctx.filter = `blur(${radius}px)`;
    ctx.drawImage(source, 0, 0);
    ctx.filter = "none";
    return out;
  }
  const k = Math.max(1, Math.floor(radius / 4));
  const w = Math.max(1, Math.round(out.width / k));
  const h = Math.max(1, Math.round(out.height / k));
  const small = document.createElement("canvas");
  small.width = w;
  small.height = h;
  const sctx = small.getContext("2d");
  if (!sctx) throw new Error("Canvas 2D context unavailable");
  sctx.imageSmoothingQuality = "high";
  sctx.drawImage(source, 0, 0, w, h);
  const image = sctx.getImageData(0, 0, w, h);
  gaussianBlurRGBA(image.data, w, h, radius / k);
  sctx.putImageData(image, 0, 0);
  ctx.imageSmoothingQuality = "high";
  ctx.drawImage(small, 0, 0, out.width, out.height);
  return out;
}

At a 16 px radius k is 4, so the pixel loop touches one sixteenth of the pixels. On a 12-megapixel phone photo that is the difference between a pause and a freeze, and it keeps the ImageData buffer small on a device that does not have much memory to spare.

Two related traps

Drop shadows. filter: drop-shadow(...) has the same problem. The canvas shadow properties work everywhere, with one conversion: shadowBlur is twice the standard deviation, so a CSS drop-shadow(0 8px 12px …) becomes shadowOffsetY = 8 and shadowBlur = 24.

Anything else in the filter string. brightness(), grayscale(), contrast() and the rest are equally inert. They are per-pixel operations, so a short loop over getImageData replaces them.

Testing the Safari path without Safari

You can remove the property in Chromium and run the same tests against the fallback:

await page.evaluate(() => {
  delete CanvasRenderingContext2D.prototype.filter;
});

Run it after the page has loaded. If your detection caches its answer like the one above, reset the cache too, or delete the property before the first call.

Where this runs

The code above is what blurs faces and licence plates in the face blur tool on Imagic AI, a set of free image tools I build. The blur happens in the browser, so the check matters most on exactly the devices where it used to fail.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.