From 8391fd861d635407a3e0953842c0d2087d3ac6be Mon Sep 17 00:00:00 2001 From: tangying1027 <33517362+tangying1027@users.noreply.github.com> Date: Thu, 26 Oct 2023 18:10:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20autoFit=E8=87=AA=E5=8A=A8resize=20(#243?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: xuying.xu --- packages/f-react/src/createCanvas.tsx | 42 +++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/packages/f-react/src/createCanvas.tsx b/packages/f-react/src/createCanvas.tsx index e3885311..7e3589a6 100644 --- a/packages/f-react/src/createCanvas.tsx +++ b/packages/f-react/src/createCanvas.tsx @@ -14,6 +14,7 @@ export interface CanvasProps { children?: React.ReactElement | React.ReactElement[] | null; fallback?: JSX.Element | null; onError?: (error: Error) => void; + autoFit?: boolean; } export interface CanvasState { @@ -50,12 +51,21 @@ const createCanvas = (CanvasClass: typeof Canvas) => { return class ReactCanvas extends Component { canvasRef: RefObject; canvas: Canvas; + parentNode: { + width: number; + height: number; + }; + observer: MutationObserver; constructor(props: CanvasProps) { super(props); const { canvasRef } = props; this.canvasRef = canvasRef || createRef(); this.state = { error: null }; + this.parentNode = { + width: 0, + height: 0, + }; } catchError(error) { @@ -99,6 +109,34 @@ const createCanvas = (CanvasClass: typeof Canvas) => { canvas.render().catch((error) => { this.catchError(error); }); + + this.observeElement(); + } + + observeElement() { + if (!this.props?.autoFit) return; + const targetNode = this.canvasRef.current?.parentElement; + window?.addEventListener('resize', () => { + this.resize(); + }); + + const observerConfig = { attributes: true }; + this.observer = new MutationObserver(() => { + this.resize(); + }); + this.observer.observe(targetNode, observerConfig); + } + + resize() { + const targetNode = this.canvasRef.current?.parentElement; + const { width: lastWidth, height: lastHeight } = targetNode.getBoundingClientRect(); + if (lastWidth === this.parentNode.width && lastHeight === this.parentNode.height) return; + this.parentNode = { + width: lastWidth, + height: lastHeight, + }; + + this.canvas.resize(lastWidth, lastHeight); } componentDidUpdate() { @@ -146,6 +184,10 @@ const createCanvas = (CanvasClass: typeof Canvas) => { if (!canvas) return; canvas.destroy(); this.canvas = null; + + if (!this.observer) return; + this.observer.disconnect(); + this.observer = null; } }; };