tanmya
tanmya

Reputation: 103

How to Add styling to Image Component in React Konva

I am complete beginner in react konva. I am using Image component with the use-image hook to display a picture but I want the picture to be round. I tried different css approach but nothing seems to work. Any Help is much appreciated

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

const [image] = useImage(picture);

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

Upvotes: 0

Views: 576

Answers (1)

lavrton
lavrton

Reputation: 20373

Konva.Image doesn't have border radius property. It is not a DOM element, so you can't apply CSS styles to it.

You can emulate border radius effect with 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>
  );
};

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

Upvotes: 1

Related Questions