React+TypeScriptでCanvasを用いて矩形描画をする関数コンポーネントです。
import React, { useEffect, useRef, memo, FC } from 'react';
type Props = {
canvasWidth: number; //canvas幅
canvasHeight: number; //canvas高さ
x: number; //矩形始点x
y: number; //矩形始点y
rectWidth: number; //矩形幅
rectHeight: number; //矩形高さ
};
const Canvas: FC<Props> = ({
canvasWidth,
canvasHeight,
x,
y,
rectWidth,
rectHeight
}) => {
const canvasRef = useRef(null);
const getContext = (): CanvasRenderingContext2D => {
const canvas: any = canvasRef.current;
return canvas.getContext('2d');
};
useEffect(() => {
const ctx = getContext();
ctx.strokeStyle = '#000000'; // 矩形色
ctx.lineWidth = 2; // 矩形線幅
ctx.strokeRect(x, y, rectWidth, rectHeight); // 矩形描画
}, [canvasWidth, canvasHeight, x, y, rectWidth, rectHeight]);
return <canvas ref={canvasRef} width={canvasWidth} height={canvasHeight} />;
};
export default memo(Canvas);