首页 > 解决方案 > ReactJS KonvasJS 如何创建不能重叠的 2 层

问题描述

我正在尝试创建 2 个不能重叠的图层(图像),因此它们仍然可以自由拖动,但不会相互显示。

我尝试过使用 zIndex 或空白 Rect,但无法弄清楚如何制作 2 个不能重叠的可拖动图层(非常类似于溢出:隐藏行为)

附上一个 GIF 来显示问题,每一层都不应该在分隔线后面可见。

2 重叠的图像

return (
<Stage width={size.width} height={size.height}>

  {stateImages.map((imageConfig) => {
    index++
    return <Layer><Image
      x={size.width/2 * index}
      y={0}
      image={imageConfig.image}
      draggable
    />
    </Layer>
  })}

  {stateImages.length > 1 &&
  <Layer>
    <Rect
      x={size.width / 2}
      y={0}
      width={4}
      height={size.height}
      fill="white"
      shadowBlur={10}
      zIndex={2}
    />
  </Layer>
  }

</Stage>

)

标签: reactjskonvajsreact-konvakonvajs-reactjs

解决方案


You can use clip https://konvajs.org/docs/clipping/Clipping_Regions.html#page-title for that use case:

import React, { Component } from "react";
import { render } from "react-dom";
import { Stage, Layer, Image, Group } from "react-konva";
import useImage from "use-image";

// the first very simple and recommended way:
const MyImage = () => {
  const [image] = useImage("https://i.imgur.com/ktWThtZ.png");
  return <Image image={image} draggable />;
};

class App extends Component {
  render() {
    return (
      <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
          <Group
            clipX={0}
            clipY={0}
            clipWidth={window.innerWidth / 2}
            clipHeight={window.innerHeight}
          >
            <MyImage />
          </Group>
          <Group
            x={window.innerWidth / 2}
            clipX={0}
            clipY={0}
            clipWidth={window.innerWidth / 2}
            clipHeight={window.innerHeight}
          >
            <MyImage />
          </Group>
        </Layer>
      </Stage>
    );
  }
}

render(<App />, document.getElementById("root"));

https://codesandbox.io/s/react-konva-clip-images-demo-onp3w?file=/src/index.js


推荐阅读