glodrei
Version:
useful add-ons for react-three-fiber
76 lines (67 loc) • 1.91 kB
text/mdx
title: Center
sourcecode: src/core/Center.tsx
[](https://drei.pmnd.rs/?path=/story/staging-center--default-story)
<Grid cols={4}>
<li>
<Codesandbox id="x6obrb" />
</li>
<li>
<Codesandbox id="v8s9ij" />
</li>
</Grid>
Calculates a boundary box and centers its children accordingly.
```tsx
export type Props = JSX.IntrinsicElements['group'] & {
top?: boolean
right?: boolean
bottom?: boolean
left?: boolean
front?: boolean
back?: boolean
/** Disable all axes */
disable?: boolean
/** Disable x-axis centering */
disableX?: boolean
/** Disable y-axis centering */
disableY?: boolean
/** Disable z-axis centering */
disableZ?: boolean
/** Precision, defaults to true, see https://threejs.org/docs/index.html?q=box3#api/en/math/Box3.setFromObject */
precise?: boolean
/** Callback, fires in the useLayoutEffect phase, after measurement */
onCentered?: (props: OnCenterCallbackProps) => void
}
```
```tsx
type OnCenterCallbackProps = {
/** The next parent above <Center> */
parent: THREE.Object3D
/** The outmost container group of the <Center> component */
container: THREE.Object3D
width: number
height: number
depth: number
boundingBox: THREE.Box3
boundingSphere: THREE.Sphere
center: THREE.Vector3
verticalAlignment: number
horizontalAlignment: number
depthAlignment: number
}
```
```jsx
<Center top left>
<mesh />
</Center>
```
Optionally you can define `onCentered` which calls you back when contents have been measured. This would allow you to easily scale to fit. The following for instance fits a model to screen height.
```jsx
function ScaledModel() {
const viewport = useThree((state) => state.viewport)
return (
<Center onCentered={({ container, height }) => container.scale.setScalar(viewport.height / height)}>
<Model />
</Center>
```