Konva 过滤器不遵循过滤器的 CSS 规范。 Konva 过滤器可能有不同的行为并接受不同的参数。因此,使用内置过滤器可能很难重现相同的结果。
你有两个选择:
1。自定义过滤器。
在Custom Filter Tutorial 之后,您可以编写您的过滤器函数并根据需要操作像素。对于您的用例,您可以大大简化逻辑。例如,只需将具有某种颜色的像素替换为具有另一种颜色的像素。
你可以在这里 100% 替换所有的 CSS 过滤器,但这不是一件小事。
// lets define a custom filter:
var ColorReplaceFilter = function (imageData) {
var nPixels = imageData.data.length;
for (var i = 0; i < nPixels - 4; i += 4) {
const isTransparent = imageData.data[i + 3] === 0;
if (!isTransparent) {
imageData.data[i] = 90;
imageData.data[i + 1] = 149;
imageData.data[i + 2] = 246;
}
}
};
const CustomFilterImage = () => {
const [image] = useImage(URL, "Anonimus");
const imageRef = React.useRef();
// when image is loaded we need to cache the shape
React.useEffect(() => {
if (image) {
// you many need to reapply cache on some props changes like shadow, stroke, etc.
imageRef.current.cache();
}
}, [image]);
return (
<Image
ref={imageRef}
x={100}
y={10}
image={image}
filters={[ColorReplaceFilter]}
blurRadius={10}
/>
);
};
2。 context.filter API。
您可以使用CanvasRenderingContext2D.filter 属性在画布元素上应用 CSS 过滤器。对于演示,我将在外部画布中绘制图像以仅在其上应用过滤器,而不是整个 Konva 层。
请注意,在撰写此答案时,并非所有浏览器都支持该 API!
const FilterViaCanvasImage = () => {
const [image] = useImage(URL, "Anonimus");
const canvas = React.useMemo(() => {
if (!image) {
return undefined;
}
const el = document.createElement("canvas");
el.width = image.width;
el.height = image.height;
const ctx = el.getContext("2d");
ctx.filter =
"invert(51%) sepia(81%) saturate(1433%) hue-rotate(195deg) brightness(100%) contrast(93%)";
ctx.drawImage(image, 0, 0);
return el;
}, [image]);
return (
<Image
x={10}
y={10}
image={canvas}
filters={[Konva.Filters.HSV]}
hue={110}
saturation={10}
value={100}
/>
);
};
两种情况的演示:https://codesandbox.io/s/react-konva-color-replace-filters-fqy2q