UNPKG

@isaac_ua/drei-html-fix

Version:

drei-html-fix is a React utility that resolves alignment and offset issues with the Html component from @react-three/drei

61 lines (60 loc) 1.85 kB
// src/components/CanvasWrapper.tsx import { Canvas, useThree } from "@react-three/fiber"; import React, { useEffect, useRef, useState } from "react"; var CanvasWrapper = ({ children, canvasProps = {} }) => { const containerRef = useRef(null); const [size, setSize] = useState({ width: 0, height: 0 }); useEffect(() => { if (!containerRef.current) return; const observer = new ResizeObserver(([entry]) => { const { width, height } = entry.contentRect; setSize({ width: Math.round(width % 2 !== 0 ? width + 1 : width), height: Math.round(height % 2 !== 0 ? height + 1 : height) }); }); observer.observe(containerRef.current); return () => observer.disconnect(); }, []); return /* @__PURE__ */ React.createElement( "div", { ref: containerRef, style: { width: "100vw", height: "100dvh", overflow: "hidden" } }, /* @__PURE__ */ React.createElement( Canvas, { ...canvasProps, style: { ...canvasProps == null ? void 0 : canvasProps.style, width: size.width, height: size.height } }, /* @__PURE__ */ React.createElement(InvalidateOnResize, null), /* @__PURE__ */ React.createElement(UpdateCameraOnResize, null), children ) ); }; var InvalidateOnResize = () => { const { invalidate } = useThree(); useEffect(() => { const handle = () => invalidate(); window.addEventListener("resize", handle); return () => window.removeEventListener("resize", handle); }, [invalidate]); return null; }; var UpdateCameraOnResize = () => { const { camera, size } = useThree(); useEffect(() => { camera.aspect = size.width / size.height; camera.updateProjectionMatrix(); }, [camera, size.width, size.height]); return null; }; export { CanvasWrapper };