diff --git a/package.json b/package.json index b89dea4..025a804 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,8 @@ }, "homepage": "https://github.com/pmndrs/react-three-csg#readme", "dependencies": { - "mitt": "^3.0.0" + "mitt": "^3.0.0", + "react-merge-refs": "^2.1.1" }, "peerDependencies": { "@react-three/fiber": ">=8.0.0", diff --git a/src/Canvas.tsx b/src/Canvas.tsx index 57060fd..5d3d9b1 100644 --- a/src/Canvas.tsx +++ b/src/Canvas.tsx @@ -1,5 +1,6 @@ import React, { useEffect, useRef } from 'react' -import type { Options as ResizeOptions } from 'react-use-measure' +import useMeasure, { Options as ResizeOptions } from 'react-use-measure' +import { mergeRefs } from 'react-merge-refs' import { Canvas as CanvasImpl, RenderProps } from '@react-three/fiber' import { EVENTS } from './events' @@ -25,7 +26,9 @@ function isRefObject(ref: any): ref is React.MutableRefObject { export function Canvas({ eventSource, worker, fallback, style, className, id, ...props }: CanvasProps) { const [shouldFallback, setFallback] = React.useState(false) + const [measureRef, bounds] = useMeasure(props.resize) const canvasRef = useRef(null!) + const mergedRef = mergeRefs([canvasRef, measureRef]) const hasTransferredToOffscreen = useRef(false) useEffect(() => { @@ -110,25 +113,20 @@ export function Canvas({ eventSource, worker, fallback, style, className, id, .. { passive } ) }) - - const handleResize = () => { - worker.postMessage({ - type: 'resize', - payload: { - width: currentEventSource.clientWidth, - height: currentEventSource.clientHeight, - top: currentEventSource.offsetTop, - left: currentEventSource.offsetLeft, - }, - }) - } - - window.addEventListener('resize', handleResize) - return () => { - window.removeEventListener('resize', handleResize) - } }, [worker]) + useEffect(() => { + worker.postMessage({ + type: 'resize', + payload: { + width: bounds.width, + height: bounds.height, + top: bounds.top, + left: bounds.left, + }, + }) + }, [bounds]) + useEffect(() => { if (!worker) return worker.postMessage({ type: 'props', payload: props }) @@ -143,7 +141,7 @@ export function Canvas({ eventSource, worker, fallback, style, className, id, .. id={id} className={className} style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', display: 'block', ...style }} - ref={canvasRef} + ref={mergedRef} /> ) }