Skip to content

Instantly share code, notes, and snippets.

@Kaiido
Last active October 8, 2021 05:12
Show Gist options
  • Save Kaiido/45d189c110d29ac2eda25a7762c470f2 to your computer and use it in GitHub Desktop.
Save Kaiido/45d189c110d29ac2eda25a7762c470f2 to your computer and use it in GitHub Desktop.
Get all supported CanvasFilter filters
/**
* MIT License - Copyright (c) 2021 Kaiido
*
* A method that returns a Set of all the SVG filters
* that are supported as CanvasFilter by the current UA.
* See https://github.com/whatwg/html/pull/6763#discussion_r691322778
*
**/
function getSupportedCanvasFilters() {
const supported = new Set();
// CanvasFilter is not available, no test to run
if (!("CanvasFilter" in globalThis)) {
return supported;
}
// The list of SVG filters elements (in CanvasFilter format, i.e -"fe"),
// and an attribute that should be read per filter:
const map = {
blend: "mode",
colorMatrix: "type",
componentTransfer: "funcR",
composite: "operator",
convolveMatrix: "kernelMatrix",
diffuseLighting: "surfaceScale",
displacementMap: "scale",
dropShadow: "stdDeviation",
flood: "floodColor", // will this be camelCased?
gaussianBlur: "stdDeviation",
// t.b.d. image:
// t.b.d. merge:
morphology: "operator",
offset: "dx",
specularLighting: "surfaceScale",
// t.b.d. tile:
turbulence: "seed"
};
for (const [ filter, prop ] of Object.entries(map)) {
try {
new CanvasFilter(
{
filter,
get [prop]() {
supported.add(filter);
// throw to avoid the actual creation of the CanvasFilter
throw "don't exec";
},
}
);
}
catch(err) {
if (err !== "don't exec") {
// thrown before our own getter prop was reached
// this means we support this filter
supported.add(filter)
}
}
}
return supported;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment