Home > Mobile >  React Konva: onMouseOver doesn't trigger when a shape above it is removed?
React Konva: onMouseOver doesn't trigger when a shape above it is removed?

Time:10-27

I have a project with two <Rect/> on top of each other.
The <Rect/> at the bottom changes its color when the cursor is hovering over it.

export const BottomSquare = () => {
  const [color, setColor] = useState("green");
  return (
    <Rect
      width={100}
      height={100}
      opacity={1}
      fill={color}
      onm ouseOver={() => {
        setColor("blue");
      }}
      onm ouseLeave={() => {
        setColor("green");
      }}
    />
  );
};

the <Rect/> at the top changes its position to be away from the bottom <Rect/> when it's clicked. This <Rect/> is smaller than the bottom one.

export const TopSquare = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  return (
    <Rect
      {...position}
      width={50}
      height={50}
      opacity={1}
      fill="grey"
      onClick={(event) => {
        setPosition({ x: 100, y: 100 });
      }}
    />
  );
};

Hovering over the top <Rect/> does not trigger the color changing logic of the bottom <Rect/>, which is the expected behavior.

However, when clicking on the top <Rect/>, and it's moved away, making the cursor to hovering over the bottom <Rect/>, the onMouseOver() logic doesn't trigger unless I move the cursor for at least 1 pixel. This feels like a onMouseMove() behavior rather than onMouseOver().

react-konva onm ouseOver issue

What I want is for the bottom <Rect/> to be able to trigger the onMouseOver() logic when the top one is removed.

I tried onMouseEnter() and onMouseMove(), but the issue is still there.

How can I solve this issue?

reproduced example on codesandbox.io

CodePudding user response:

You could e.g. get the reference to the bottom rect by applying some id to it and then programatically start the mouseover event when user clicks on the top rect.

Working example: https://codesandbox.io/s/gracious-hugle-bzj4jx

export const TopSquare = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  return (
    <Rect
      {...position}
      width={50}
      height={50}
      opacity={1}
      fill="grey"
      onClick={(event) => {
        const stage = event.target.getStage();
        const node = stage?.findOne('#bottomRect');
        node?.fire('mouseover');
        setPosition({ x: 100, y: 100 });
      }}
    />
  );
};

export const BottomSquare = () => {
  const [color, setColor] = useState("green");
  return (
    <Rect
      width={100}
      height={100}
      id="bottomRect"
      opacity={1}
      fill={color}
      onm ouseOver={() => {
        setColor("blue");
      }}
      onm ouseLeave={() => {
        setColor("green");
      }}
    />
  );
};
  • Related