Skip to content

Commit

Permalink
feat: autoFit自动resize (#243)
Browse files Browse the repository at this point in the history
Co-authored-by: xuying.xu <[email protected]>
  • Loading branch information
tangying1027 and xuying.xu authored Oct 26, 2023
1 parent 5c64d3e commit 8391fd8
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions packages/f-react/src/createCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -50,12 +51,21 @@ const createCanvas = (CanvasClass: typeof Canvas) => {
return class ReactCanvas extends Component<CanvasProps, CanvasState> {
canvasRef: RefObject<HTMLCanvasElement>;
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) {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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;
}
};
};
Expand Down

0 comments on commit 8391fd8

Please sign in to comment.