javascriptreactjsnode.jsreact-konva

How to add border radius to react-konva Image element


I'm using React-konva to make some draggable components. Here is my code:


const URLImage = ({ image, isSelected, onSelect, onTransform }) => {
  const imageRef = useRef();
  const trRef = useRef();
  const [img] = useImage(image.src);


  useEffect(() => {
    if (isSelected) {
      // we need to attach transformer manually
      trRef.current.nodes([imageRef.current]);
      trRef.current.getLayer().batchDraw();
    }
  }, [isSelected]);

  return (
    <>
    <Group>
      <KonvaImage
        ref={imageRef}
        image={img}
        x={image.middle ? image.x - image.width / (2 / image.scaleX) : image.x}
        y={image.middle ? image.y - image.height / (2 / image.scaleY) : image.y}
        width={image.width}
        stroke="rgba(255, 255, 255, 0.1)" // Add a transparent outline
        strokeWidth={1} // Adjust the thickness of the outline
        height={image.height}
        scaleX={image.scaleX}
        scaleY={image.scaleY}
        draggable={image.draggable} // Make image with id 1 unmovable
        onClick={onSelect} // Handle mouse events
        onTap={onSelect} // Handle touch events
        onDragEnd={(e) => {
          image.middle = false;
          image.x = e.target.x();
          image.y = e.target.y();
        }}
        onTransformEnd={(e) => {
          image.middle = false;
          image.x = e.target.x();
          image.y = e.target.y();

          // Update the scale
          image.scaleX = e.target.scaleX();
          image.scaleY = e.target.scaleY();

          onTransform();
        }}
      />
      {isSelected && <Transformer ref={trRef} />}
      </Group>
    </>
  );
};

I want to add a border radius to it.

I also saw this question, however it didn't help me, My code just got errors.

Can someone give me a solution, Thanks in advance


Solution

  • It is supported in the last konva version via cornerRadius property:

    https://konvajs.org/api/Konva.Image.html#cornerRadius

    <KonvaImage
      cornerRadius={10}
      {...otherProperties}
    />