我想在
konva
中将 react
用于我的应用程序,但我没有看到如何制作网格的示例。我看到这个例子是为了 vanilla javascript
,但不是为了 react
。
你能给我看一下这个网格的例子吗
react
?
这是一个例子:
function drawLinesSolution4(){
// set clip function to stop leaking lines into non-viewable space.
gridLayer.clip({
x: viewRect.x1,
y: viewRect.y1,
width: viewRect.x2 - viewRect.x1,
height: viewRect.y2 - viewRect.y1
});
let fullRect = gridFullRect;
const
// find the x & y size of the grid
xSize = (fullRect.x2 - fullRect.x1),
ySize = (fullRect.y2 - fullRect.y1),
// compute the number of steps required on each axis.
xSteps = Math.round(xSize/ stepSize),
ySteps = Math.round(ySize / stepSize);
// draw vertical lines
for (let i = 0; i <= xSteps; i++) {
this.gridLayer.add(
new Konva.Line({
x: fullRect.x1 + i * stepSize,
y: fullRect.y1,
points: [0, 0, 0, ySize],
stroke: 'rgba(0, 0, 0, 0.2)',
strokeWidth: 1,
})
);
}
//draw Horizontal lines
for (let i = 0; i <= ySteps; i++) {
this.gridLayer.add(
new Konva.Line({
x: fullRect.x1,
y: fullRect.y1 + i * stepSize,
points: [0, 0, xSize, 0],
stroke: 'rgba(0, 0, 0, 0.2)',
strokeWidth: 1,
})
);
}
this.gridLayer.batchDraw();
}
更好的解决方案是让网格覆盖整个视口区域,如下图所示。
这是非常通用的网格视图,我还没有自定义它,如果看看它并了解我的话。
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
import React from 'react';
import { Stage, Layer, Rect } from 'react-konva';
function App() {
const gridSize = 10; // cells in the grid
const cellSize = 50; // size of each cell in pixels
const grid = Array.from({ length: gridSize }, (_, row) =>
Array.from({ length: gridSize }, (_, col) => ({
x: col * cellSize,
y: row * cellSize,
width: cellSize,
height: cellSize,
fill: 'white',
stroke: 'black',
strokeWidth: 1,
}))
);
return (
<Stage width={gridSize * cellSize} height={gridSize * cellSize}>
<Layer>
{grid.map((row, rowIndex) =>
row.map((cell, colIndex) => (
<Rect key={`${rowIndex}-${colIndex}`} {...cell} />
))
)}
</Layer>
</Stage>
);
// };
}
export default App;