Fixes disappearing canvas grid lines

This commit is contained in:
psychedelicious 2022-11-13 22:42:07 +11:00 committed by blessedcoolant
parent c223d93b4d
commit 73099af6ec

View File

@ -1,24 +1,54 @@
// Grid drawing adapted from https://longviewcoder.com/2021/12/08/konva-a-better-grid/
import { useColorMode } from '@chakra-ui/react';
import { createSelector } from '@reduxjs/toolkit';
import { useAppSelector } from 'app/store';
import _ from 'lodash';
import {
ReactNode,
useCallback,
useEffect,
useLayoutEffect,
useState,
} from 'react';
import { Group, Line as KonvaLine } from 'react-konva';
import { currentCanvasSelector } from './canvasSlice';
import useUnscaleCanvasValue from './hooks/useUnscaleCanvasValue';
import { stageRef } from './IAICanvas';
const selector = createSelector(
[currentCanvasSelector],
(currentCanvas) => {
const { stageScale, stageCoordinates, stageDimensions } = currentCanvas;
return { stageScale, stageCoordinates, stageDimensions };
},
{
memoizeOptions: {
resultEqualityCheck: _.isEqual,
},
}
);
const IAICanvasGrid = () => {
const { colorMode } = useColorMode();
const unscale = useUnscaleCanvasValue();
// const unscale = useUnscaleCanvasValue();
const { stageScale, stageCoordinates, stageDimensions } =
useAppSelector(selector);
const [gridLines, setGridLines] = useState<ReactNode[]>([]);
if (!stageRef.current) return null;
const unscale = useCallback(
(value: number) => {
return value / stageScale;
},
[stageScale]
);
useLayoutEffect(() => {
const gridLineColor =
colorMode === 'light' ? 'rgba(0,0,0,0.3)' : 'rgba(255,255,255,0.3)';
colorMode === 'light' ? 'rgba(136, 136, 136, 1)' : 'rgba(84, 84, 84, 1)';
const stage = stageRef.current;
const width = stage.width();
const height = stage.height();
const x = stage.x();
const y = stage.y();
const { width, height } = stageDimensions;
const { x, y } = stageCoordinates;
const stageRect = {
x1: 0,
@ -59,9 +89,7 @@ const IAICanvasGrid = () => {
xSteps = Math.round(xSize / 64) + 1,
ySteps = Math.round(ySize / 64) + 1;
return (
<Group>
{_.range(0, xSteps).map((i) => (
const xLines = _.range(0, xSteps).map((i) => (
<KonvaLine
key={`x_${i}`}
x={fullRect.x1 + i * 64}
@ -70,8 +98,8 @@ const IAICanvasGrid = () => {
stroke={gridLineColor}
strokeWidth={1}
/>
))}
{_.range(0, ySteps).map((i) => (
));
const yLines = _.range(0, ySteps).map((i) => (
<KonvaLine
key={`y_${i}`}
x={fullRect.x1}
@ -80,9 +108,12 @@ const IAICanvasGrid = () => {
stroke={gridLineColor}
strokeWidth={1}
/>
))}
</Group>
);
));
setGridLines(xLines.concat(yLines));
}, [stageScale, stageCoordinates, stageDimensions, colorMode, unscale]);
return <Group>{gridLines}</Group>;
};
export default IAICanvasGrid;