Skip to content

calculateSize()

此函数属于 Iconify Utils 包

当仅提供一个属性时,函数 calculateSize() 用于计算图标的 widthheight

例如,如果你有一个带有 viewBox="0 0 36 24" 的图标,且 height 设置为 "1em",则此函数用于计算 width 属性,其结果将为 "1.5em"。

该函数由 iconToSVG() 调用以生成属性。它也可用于图标选择器等场景,当用户输入 height 值时,你可以显示 width 值的提示。

用法

该函数包含以下参数:

  • sizestring|number。单个维度,例如 height
  • rationumber。尺寸比例。如果在第一个参数中提供 height,则第二个参数应为图标 viewBoxwidth / height。如果在第一个参数中提供 width,则第二个参数应为图标 viewBoxheight / width
  • precisionnumber。可选参数,默认值为 100

函数返回计算后的尺寸。

示例

examples.ts
tsimport { icons } from '@iconify-json/fa-regular';
import { getIconData, calculateSize, defaultIconProps } from '@iconify/utils';

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

// Add default values by merging default props and partial icon data
// Otherwise width and height might be missing
const fullIconData = {
   ...defaultIconProps,
   ...iconData,
};

// Calculate width when height is set
const calculateWidth = (height: number | string) => {
   const width = calculateSize(height, fullIconData.width / fullIconData.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, fullIconData.height / fullIconData.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"