Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is this canvas resize hook a useful addition? #205

Open
petervdn opened this issue Jul 5, 2023 · 2 comments
Open

Is this canvas resize hook a useful addition? #205

petervdn opened this issue Jul 5, 2023 · 2 comments

Comments

@petervdn
Copy link
Contributor

petervdn commented Jul 5, 2023

I'm using this in a personal project, was wondering if it could be of use here.

type Props = {
  width: number;
  height: number;
  canvasRef: RefObject<HTMLCanvasElement | null>;
};

export function useSizedCanvas({ canvasRef, height, width }: Props) {
  useEffect(() => {
    if (!canvasRef.current) {
      return;
    }

    canvasRef.current.style.width = `${width}px`;
    canvasRef.current.style.height = `${height}px`;
    canvasRef.current.width = width * window.devicePixelRatio;
    canvasRef.current.height = height * window.devicePixelRatio;
  }, [width, height, canvasRef]);
}
@ReneDrie
Copy link
Contributor

ReneDrie commented Jul 5, 2023

I think this definitely could be yeah! But I would maybe even expand it and have a useCanvas hook or something. Doing this and also returning a ref with the context perhaps?

I use this in my project:

export function useCanvas(
  wrapperRef: RefObject<HTMLElement>,
  canvasElement: RefObject<HTMLCanvasElement>,
): {
  contextRef: MutableRefObject<CanvasRenderingContext2D | null>;
} {
  const contextRef = useRef<CanvasRenderingContext2D | null>(null);

  const onResize = useCallback(() => {
    if (!wrapperRef.current || !canvasElement.current) {
      return;
    }
    const { clientWidth, clientHeight } = wrapperRef.current;
    const { devicePixelRatio } = window;
    canvasElement.current.width = clientWidth * devicePixelRatio;
    canvasElement.current.height = clientHeight * devicePixelRatio;
  }, [wrapperRef.current]);

  useResizeObserver(wrapperRef, onResize);

  useMount(() => {
    contextRef.current = canvasElement.current?.getContext('2d') ?? null;
  });

  return {
    contextRef,
  };
}

@petervdn
Copy link
Contributor Author

petervdn commented Jul 6, 2023

Why is that not in the hooks lib yet? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants