雪山飞胡
雪山飞胡

Reputation: 1

How to make shape only show in react and partially hide on stage

I created a responsive rect as an artboard in the stage, and when I add shapes and move them, I want the shapes to only show on the rect, just like opening a window on the stage, only show the shapes inside the window

Upvotes: 0

Views: 264

Answers (1)

lavrton
lavrton

Reputation: 20298

You should use clipping for that. Tutorial: https://konvajs.org/docs/clipping/Clipping_Regions.html

import React from "react";
import { createRoot } from "react-dom/client";
import { Stage, Layer, Star } from "react-konva";

function generateShapes() {
  return [...Array(50)].map((_, i) => ({
    id: i.toString(),
    x: Math.random() * window.innerWidth,
    y: Math.random() * window.innerHeight,
    rotation: Math.random() * 180,
    isDragging: false
  }));
}

const INITIAL_STATE = generateShapes();

const STAR_PROPS = {
  numPoints: 5,
  innerRadius: 20,
  outerRadius: 40,
  fill: "#89b717",
  opacity: 0.8,
  shadowColorL: "black",
  shadowBlur: 10,
  shadowOpacity: 0.6,
  shadowOffsetX: 5,
  shadowOffsetY: 5,
  scaleX: 1,
  scaleY: 1,
  draggable: true
};

const App = () => {
  const [stars] = React.useState(INITIAL_STATE);

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer
        clipX={50}
        clipY={50}
        clipWidth={window.innerWidth - 100}
        clipHeight={window.innerWidth - 100}
      >
        {stars.map((star) => (
          <Star
            {...STAR_PROPS}
            key={star.id}
            id={star.id}
            x={star.x}
            y={star.y}
            rotation={star.rotation}
          />
        ))}
      </Layer>
    </Stage>
  );
};

const container = document.getElementById("root");
const root = createRoot(container);
root.render(<App />);

https://codesandbox.io/s/react-konva-clipping-sg2fpd

Upvotes: 0

Related Questions