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 translucent = hasTransparency(data);
if (translucent) premultiplyAlpha(data);
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);
}
if (translucent) unpremultiplyAlpha(data);
}
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.
Transparent images: premultiply first
Added after publishing. The first version of this post blurred the channels as they come, and two readers pointed out in the comments what that does to a cut-out. They were right.
getImageData returns straight alpha, and a fully transparent pixel reads as (0, 0, 0, 0). Average that black into its neighbours and every soft edge goes dark: with opaque red next to transparency, the pixel at half alpha came out with R at about 127 instead of 255. Weighting the colour by alpha before the blur and dividing it back out afterwards fixes it, and it is what the browser's own filter does.
function hasTransparency(data: Uint8ClampedArray): boolean {
for (let i = 3; i < data.length; i += 4) if (data[i] !== 255) return true;
return false;
}
function premultiplyAlpha(data: Uint8ClampedArray): void {
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3];
if (a === 255) continue;
data[i] = (data[i] * a) / 255;
data[i + 1] = (data[i + 1] * a) / 255;
data[i + 2] = (data[i + 2] * a) / 255;
}
}
function unpremultiplyAlpha(data: Uint8ClampedArray): void {
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3];
if (a === 0 || a === 255) continue;
const k = 255 / a;
data[i] *= k;
data[i + 1] *= k;
data[i + 2] *= k;
}
}
An image where every alpha is 255 skips both loops, so an ordinary photo is blurred exactly as before. The test image for this is the one a commenter suggested: saturated pixels directly beside transparent ones.
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.
Top comments (6)
Great find, and the feature detection part is the useful bit: checking whether the filter actually changed pixels rather than trusting that the property exists. That pattern works for a lot of Safari gaps.
Thanks! One clarification, since people may copy it: the check in the post doesn't look at pixels. It only asks whether
filteris defined onCanvasRenderingContext2D.prototype. That's cheap and synchronous, and it's enough for Safari today because the property simply isn't there.A pixel test is the stricter version of what you describe: draw a hard black/white edge with
ctx.filter = "blur(2px)", read it back withgetImageData, and check whether the edge softened. That would also catch a browser that exposes the property but doesn't apply it. The cost is a canvas readback, so I'd run it once and cache the result.Good clarification, thanks. The property check is the right default for today, and the one-time cached pixel test is a nice upgrade path for anyone who wants to catch a browser that exposes
filterwithout applying it.For the fallback, test a transparent image with saturated pixels next to transparent ones. Blurring straight RGBA channels can introduce color fringes; premultiplying RGB by alpha before the blur and unpremultiplying afterward helps preserve the edge.
Nice catch on checking the prototype instead of reading the property back, that false positive is easy to miss. One question on the fallback: getImageData returns non-premultiplied RGBA, so if you ever blur a region with semi-transparent edges, wouldn't blurring each channel independently bleed the colour of the transparent pixels into the rim? Do you premultiply first, or is it only meant for opaque photos?
You're right, and so is @komopdf above. As first posted it blurred straight alpha, so it was only correct for opaque photos, which is all I had tested it on. I reproduced your case with opaque red next to transparency: the pixel at half alpha came out with R around 127 instead of 255, a dark rim.
It now premultiplies before the box passes and divides back out afterwards, and skips both when every alpha is 255, so ordinary photos take the same path as before. I've added that to the post under "Transparent images: premultiply first", and the red-beside-transparent case is now the regression test. Thanks for reading it that closely.