如何在 React Konva 中为图像组件添加样式

How to Add styling to Image Component in React Konva

我是 react konva 的初学者。我正在使用带有 use-image 挂钩的 Image 组件来显示图片,但我希望图片是圆形的。我尝试了不同的 css 方法,但似乎没有任何效果。非常感谢任何帮助

import picture from "../assets/pic.jpg";

const [image] = useImage(picture);

<Stage>
<Layer><Image borderRadius="50%" image={image} /></Layer>
</Stage>

Konva.Image 没有边框半径 属性。它不是 DOM 元素,因此您不能对其应用 CSS 样式。

您可以使用 group clipping 模拟边框半径效果。

const RoundedImage = ({}) => {
  const [image] = useImage("http://konvajs.github.io/assets/darth-vader.jpg");
  return (
    <Group
      clipFunc={(ctx) => {
        const cornerRadius = 20;
        const width = image ? image.width : 0;
        const height = image ? image.height : 0;
        ctx.beginPath();
        ctx.moveTo(cornerRadius, 0);
        ctx.lineTo(width - cornerRadius, 0);
        ctx.quadraticCurveTo(width, 0, width, cornerRadius);
        ctx.lineTo(width, height - cornerRadius);
        ctx.quadraticCurveTo(width, height, width - cornerRadius, height);
        ctx.lineTo(cornerRadius, height);
        ctx.quadraticCurveTo(0, height, 0, height - cornerRadius);
        ctx.lineTo(0, cornerRadius);
        ctx.quadraticCurveTo(0, 0, cornerRadius, 0);
        ctx.closePath();
      }}
    >
      <Image image={image} />
    </Group>
  );
};

演示:https://codesandbox.io/s/react-konva-image-rounded-corners-2fe4h