NarraLeaf

FixedAspectRatioContainer

FixedAspectRatioContainer 组件的宽高比、尺寸属性与缩放回调

FixedAspectRatioContainer 在任意父容器内保持固定比例的舞台,内部自动测量可用空间、居中并触发尺寸更新

注意: 在播放器中使用时,仍需包裹在 GameProviders 中以共享配置

示例

"use client";

import { FixedAspectRatioContainer } from "narraleaf-react";

export default function MyViewport() {
    return (
        <FixedAspectRatioContainer
            aspectRatio={16 / 9}
            baseWidth={1920}
            minWidth={480}
            minHeight={270}
            onUpdate={({ width, height, scale }) => {
                console.log("渲染舞台", width, height, scale);
            }}
        >
            <div className="stage">
                {/* 舞台内容 */}
            </div>
        </FixedAspectRatioContainer>
    );
}

Props

  • aspectRatio: number — 宽高比,如 16 / 9
  • baseWidth: number — 基准宽度,缩放比例通过 scale = renderWidth / baseWidth 计算
  • minWidth?: number — 最小宽度,默认 0
  • minHeight?: number — 最小高度,默认 0
  • debounceMs?: number — 尺寸更新去抖时间(ms),默认延续播放器的 ratioUpdateInterval 语义;0 关闭去抖
  • onUpdate?: (metrics: { width; height; scale; containerWidth; containerHeight }) => void — 尺寸计算完成回调
  • children?: React.ReactNode — 舞台内容
  • id?: string — 透传给最外层容器
  • className?: string — 透传给最外层容器
  • [data-*?: string] — 其余 HTML 属性透传到最外层容器

组件内部使用 ResizeObserver 监听父容器尺寸变化,自动居中、缩放并保持 position: relative / margin: auto 的布局

本页目录