1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React+TypeScriptでcanvasを用いて矩形描画する

Posted at

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);

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?