calculateSize()

This function is part of Iconify Utils package.

Function calculateSize() is used for calculating icon's width or height when only one property is provided.

For example, if you have icon with viewBox="0 0 36 24" and height is set to "1em", this function is used to calculate width property, which will be "1.5em".

Function is used by iconToSVG() to generate attributes. It can also be used by things like icon pickers, where you can show hint for width value when user inputs height value.

Usage

Function has the following parameters:

  • size, string | number. One dimension, such as height.
  • ratio, number. Dimensions ratio. If you provide height in first parameter, second parameter should be width / height of icon's viewBox. If you provider width in first parameter, second parameter should be height / width of icon's viewBox.
  • precision, number. Optional, default is 100.

Function returns calculated size.

Example

examples.ts
import { icons } from '@iconify-json/fa-regular';
import { getIconData } from '@iconify/utils/lib/icon-set/get-icon';
import { calculateSize } from '@iconify/utils/lib/svg/size';

// Get 384 x 512 icon
const iconData = getIconData(icons, 'bookmark', true);
if (!iconData) {
   throw new Error('Icon is missing');
}

// Calculate width when height is set
const calculateWidth = (height: number | string) => {
   const width = calculateSize(height, iconData.width / iconData.height);
   console.log(`For height="${height}", width value is "${width}"`);
};
calculateWidth('1em');
calculateWidth(24);
calculateWidth('calc(1em + 8px)');
calculateWidth('3.25rem');

// Calculate height when width is set
const calculateHeight = (width: number | string) => {
   const height = calculateSize(width, iconData.height / iconData.width);
   console.log(`For width="${width}", height value is "${height}"`);
};
calculateHeight('2em');
calculateHeight(20);
Result:
For height="1em", width value is "0.75em"
For height="24", width value is "18"
For height="calc(1em + 8px)", width value is "calc(0.75em + 6px)"
For height="3.25rem", width value is "2.44rem"
For width="2em", height value is "2.67em"
For width="20", height value is "26.67"