0

我已经用 konva 创建了砖石网格,这里的 React 是我已经走了多远的例子: https ://codesandbox.io/s/masonry-grid-image-konva-react-cp73d

React 中关于 Konva Image 的文档https://konvajs.org/docs/react/Images.html

我需要用同一张卡片创建一个无限网格,就像这张图片一样,但我无法用背景图片或填充图案填充矩形。我不确定如何创建 img 对象来填充矩形或如何在无限网格中使用该图像重复相同的图像......它在代码和框中的 svg 这是我当前的代码:

对此的任何帮助将不胜感激

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

const CardImage = () => {
  const [image] = useImage("https://i.stack.imgur.com/7nF5K.png");
  return <Image image={image} />;
};

const WIDTH = 318;
const HEIGHT = 452;

const App = () => {
  const [stagePos, setStagePos] = React.useState({ x: 200, y: 200 });
  const startX = Math.floor((-stagePos.x - window.innerWidth) / WIDTH) * WIDTH;
  const endX = Math.floor((-stagePos.x + window.innerWidth * 2) / WIDTH) * WIDTH;
  const startY = Math.floor((-stagePos.y - window.innerHeight) / HEIGHT) * HEIGHT;
  const endY = Math.floor((-stagePos.y + window.innerHeight * 2) / HEIGHT) * HEIGHT;

  const gridComponents = [];

  for (var x = startX; x < endX; x += WIDTH) {
    for (var y = startY; y < endY; y += HEIGHT) {

      gridComponents.push(
        <>
          <Rect
            x={3.8 * x}
            y={1.2 * y}
            width={WIDTH}
            height={HEIGHT}
            stroke
            shadowBlur={20}
            cornerRadius={10}
          />
          <Rect
            x={3.8 * x + 405}
            y={1.2 * y + 200}
            width={WIDTH}
            height={HEIGHT}
            stroke
            shadowBlur={20}
            cornerRadius={10}
          />
          <Rect
            x={3.8 * x + 810}
            y={1.2 * y + 400}
            width={WIDTH}
            height={HEIGHT}
            stroke
            shadowBlur={20}
            cornerRadius={10}
          />
          <CardImage />
        </>
      );
    }
  }

  return (
    <Stage
      x={stagePos.x}
      y={stagePos.y}
      width={window.innerWidth}
      height={window.innerHeight}
      draggable
      onDragEnd={(e) => {
        setStagePos(e.currentTarget.position());
      }}
    >
      <Layer>{gridComponents}</Layer>
    </Stage>
  );
};

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

1 回答 1

2

如果你想用图像填充矩形,你可以使用fillPatternImage属性。

<Rect
  width={WIDTH}
  height={HEIGHT}
  shadowBlur={20}
  cornerRadius={10}
  fillPatternImage={image}
/>

要下载图像,您可以使用与 for 类似的方式Konva.Imageuse-image挂钩https://konvajs.org/docs/react/Images.html

const [image] = useImage("https://i.stack.imgur.com/7nF5K.png");

您更新了演示:https ://codesandbox.io/s/masonry-grid-image-konva-react-forked-s2wku?file=/src/index.js

于 2020-10-01T17:10:05.267 回答