fit-dimensions
v1.0.0
Published
A tiny utility function to fit a source rectangle within a target rectangle using popular object-fit modes (contain, cover, fill, none, scale-down). Maintains aspect ratio as needed. Useful for images, videos, UI elements, and more.
Maintainers
Readme
A tiny utility function to fit a source rectangle within a target rectangle using popular object-fit modes (contain, cover, fill, none, scale-down). Maintains aspect ratio as needed. Useful for images, videos, UI elements, and more.
Use Cases
- Fitting images, videos, or canvases into containers
- UI layout calculations
- Responsive design utilities
- Viewport-aware rendering in games or data viz
Mode
| Mode | Description | ---- | ---- | contain | Scale to fit inside target, maintain aspect ratio | cover | Fill target, cropping as needed, maintain aspect ratio | fill | Stretch to fill target, ignore aspect ratio | none | No scaling, original size | scale-down | Use smaller of none or contain
Installation
Using pnpm:
pnpm add fit-dimensionsUsing yarn:
yarn add fit-dimensionsUsing npm:
npm install fit-dimensionsUsage
Parameters
srcWidth: width of the source rectangle. (number)srcHeight: height of the source rectangle. (number)maxWidth: width of the target rectangle. (number)maxHeight: height of the target rectangle. (number)mode: one of contain | cover | fill | none | scale-down. (string) (optional) (default: contain)
Return
An object:
width: fitted width. (number)height: fitted height. (number)x: offset from the left. (number)y: offset from the top. (number)
xandyare the position used to center the fitted rectangle
Example
import { fitDimensions } from 'fit-dimensions'
// or: const { fitDimensions } = require('fit-dimensions')
// Example:
const fit = fitDimensions(800, 600, 400, 400, 'contain')
// fit = { width: 400, height: 300, x: 0, y: 50 }Authors
👤 GloryWong
- Website: https://glorywong.com
- GitHub: @GloryWong
Show Your Support
Give a ⭐️ if this project helped you!
Contributing
Contributions are welcome! If you have ideas, bug fixes, or improvements, please Open an issue or submit a pull request on the GitHub repository.
License
This project is licensed under the MIT License. See the LICENSE file for more details.
