Skip to content

Instantly share code, notes, and snippets.

@codingedgar
Created November 16, 2020 23:49
Show Gist options
  • Save codingedgar/9a2585781ee23059b05f5d4c2ccc2702 to your computer and use it in GitHub Desktop.
Save codingedgar/9a2585781ee23059b05f5d4c2ccc2702 to your computer and use it in GitHub Desktop.
Example2 draw winning line
const BOARD_SIZE = 208 as const;
const BOARD_PADDING = 4 as const;
const LINE_WIDTH = 8 as const;
const LINE_CAP_SIZE = LINE_WIDTH / 2;
const CELL_SIZE = 64 as const;
const CELL_PADDING = 4 as const;
const CELL_CENTER = CELL_SIZE / 2;
const COLOR1 = '#FFD103';
const COLOR2 = '#A303FF';
const COLOR3 = '#CCCCCC';
function WinningLineCanvas(props: {
canvasProps: React.DetailedHTMLProps<
React.CanvasHTMLAttributes<HTMLCanvasElement>,
HTMLCanvasElement
>,
lineType: ResultType
}) {
const canvas = useRef<HTMLCanvasElement>(null)
useEffect(
() => {
const lineWidth = LINE_WIDTH * 2;
const linePadding = LINE_CAP_SIZE * 2;
const lineLength = BOARD_SIZE - (linePadding * 2);
const middleOfSeparation = CELL_CENTER;
const fistCellCenter = middleOfSeparation;
const secondCellCenter = middleOfSeparation + CELL_SIZE + LINE_WIDTH;
const thirdCellCenter = middleOfSeparation + (2 * (CELL_SIZE + LINE_WIDTH));
const distanceFromBoardEdge = BOARD_PADDING + LINE_CAP_SIZE + linePadding;
const context = canvas.current!.getContext('2d')!;
context.lineWidth = lineWidth;
context.lineCap = 'round';
context.strokeStyle = COLOR1;
context.beginPath();
switch (props.lineType) {
case 'Column1':
context.moveTo(fistCellCenter, distanceFromBoardEdge);
context.lineTo(fistCellCenter, lineLength);
break;
case 'Column2':
context.moveTo(secondCellCenter, distanceFromBoardEdge);
context.lineTo(secondCellCenter, lineLength);
break;
case 'Column3':
context.moveTo(thirdCellCenter, distanceFromBoardEdge);
context.lineTo(thirdCellCenter, lineLength);
break;
case 'Row1':
context.moveTo(distanceFromBoardEdge, fistCellCenter);
context.lineTo(lineLength, fistCellCenter);
break;
case 'Row2':
context.moveTo(distanceFromBoardEdge, secondCellCenter);
context.lineTo(lineLength, secondCellCenter);
break;
case 'Row3':
context.moveTo(distanceFromBoardEdge, thirdCellCenter);
context.lineTo(lineLength, thirdCellCenter);
break;
case 'Diagonal1':
context.moveTo(distanceFromBoardEdge, distanceFromBoardEdge);
context.lineTo(lineLength, lineLength);
break;
case 'Diagonal2':
context.moveTo(lineLength, distanceFromBoardEdge);
context.lineTo(distanceFromBoardEdge, lineLength);
break;
default:
break;
}
context.stroke();
},
[canvas, props.lineType]
)
return (
<canvas
{...props.canvasProps}
height={BOARD_SIZE}
width={BOARD_SIZE}
ref={canvas}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment