Skip to content

Commit

Permalink
feat: autofit属性
Browse files Browse the repository at this point in the history
  • Loading branch information
xuying.xu committed Feb 6, 2024
1 parent 787241d commit 60f46ec
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions packages/react/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,17 @@ export interface CanvasProps {
fallback?: React.Component;
onError?: (error: Error) => void;
children?: React.ReactElement | React.ReactElement[] | null;
autoFit?: boolean;
}

class ReactCanvas extends React.Component<CanvasProps> {
canvasRef: RefObject<HTMLCanvasElement>;
canvas: Canvas;
parentNode: {
width: number;
height: number;
};
observer: ResizeObserver;

constructor(props: CanvasProps) {
super(props);
Expand All @@ -96,11 +102,44 @@ class ReactCanvas extends React.Component<CanvasProps> {
};
};

observeElement() {
if (!this.props?.autoFit) return;
const targetNode = this.canvasRef.current?.parentElement;
window?.addEventListener('resize', () => {
this.resize();
});

if (typeof ResizeObserver !== 'undefined') {
this.observer = new ResizeObserver(() => {
this.resize();
});
this.observer.observe(targetNode);
}
}

resize() {
const targetNode = this.canvasRef.current?.parentElement;
const { width: lastWidth, height: lastHeight } = targetNode.getBoundingClientRect();
if (
(lastWidth === this.parentNode.width && lastHeight === this.parentNode.height) ||
!lastWidth ||
!lastHeight
)
return;
this.parentNode = {
width: lastWidth,
height: lastHeight,
};

this.canvas.resize(lastWidth, lastHeight);
}

componentDidMount() {
const pickProps = this.getProps();
const canvas = new Canvas(pickProps);
this.canvas = canvas;
canvas.render();
this.observeElement();
}

componentDidUpdate() {
Expand Down

0 comments on commit 60f46ec

Please sign in to comment.