如何在TypeScript版Material Color Utilities中使用MD3对比度功能并生成主题?
利用Material Color Utilities生成可控对比度的MD3主题(TypeScript实现)
一、程序化生成用户可控的默认/中等/高对比度主题
Material Color Utilities提供了直接的API来生成不同对比度等级的主题,核心是通过createTheme函数的contrastLevel参数控制,结合你已有的6个调色板(primary/secondary/tertiary/neutral/neutral-variant/error)和固定颜色,步骤如下:
1. 基础准备
确保你已导入所需工具类:
import { CorePalette, Theme, createTheme } from '@material/material-color-utilities';
2. 生成不同对比度主题
Material Design 3的对比度等级对应contrastLevel参数取值:
- 默认对比度:
contrastLevel: 0 - 中等对比度:
contrastLevel: 0.5(可根据需求自定义调整,也可映射用户滑块输入值) - 高对比度:
contrastLevel: 1
示例代码:
// 导入你的自定义调色板(若已获取6个调色板数据) // const corePalette = CorePalette.fromJSON({ // primary: [/* 你的primary调色板数组 */], // secondary: [/* 你的secondary调色板数组 */], // tertiary: [/* 你的tertiary调色板数组 */], // neutral: [/* 你的neutral调色板数组 */], // neutralVariant: [/* 你的neutral-variant调色板数组 */], // error: [/* 你的error调色板数组 */], // }); // 或通过主色生成基础调色板(示例) const corePalette = CorePalette.fromHex('#6750a4'); // 生成默认对比度主题 const defaultTheme = createTheme({ corePalette, contrastLevel: 0, }); // 生成中等对比度主题 const mediumContrastTheme = createTheme({ corePalette, contrastLevel: 0.5, }); // 生成高对比度主题 const highContrastTheme = createTheme({ corePalette, contrastLevel: 1, });
3. 应用主题到UI
生成的Theme对象包含所有语义化颜色(如theme.surface、theme.onSurface),可直接映射到组件样式:
// 示例:将主题颜色注入CSS变量 function applyTheme(theme: Theme) { document.documentElement.style.setProperty('--md-sys-color-primary', theme.primary.toHexString()); document.documentElement.style.setProperty('--md-sys-color-on-primary', theme.onPrimary.toHexString()); // 其他语义化颜色(surface、error等)同理 } // 根据用户选择切换主题 switch (userSelectedContrast) { case 'default': applyTheme(defaultTheme); break; case 'medium': applyTheme(mediumContrastTheme); break; case 'high': applyTheme(highContrastTheme); break; }
二、自动控制对比度等级的方法及对应函数
Material Color Utilities支持基于系统偏好或颜色自动调整对比度,核心能力如下:
1. 基于系统偏好自动切换
通过浏览器API检测系统对比度偏好,自动生成适配主题:
// 检测系统对比度偏好 function getSystemContrastLevel(): number { const isHighContrast = window.matchMedia('(prefers-contrast: high)').matches; const isLowContrast = window.matchMedia('(prefers-contrast: low)').matches; if (isHighContrast) return 1; if (isLowContrast) return -1; return 0; // 默认对比度 } // 生成适配系统的自动主题 const autoTheme = createTheme({ corePalette, contrastLevel: getSystemContrastLevel(), });
2. 自动确保颜色对比度的核心函数
工具库中的DynamicColor类和ensureContrast函数可自动计算符合WCAG标准的颜色:
import { DynamicColor, ensureContrast, argbFromHex } from '@material/material-color-utilities'; // 示例:根据背景色自动生成符合对比度的前景色 const backgroundArgb = argbFromHex('#f5f5f5'); const foregroundColor = DynamicColor.fromPalette(corePalette.primary, 80).getColor(backgroundArgb); // 手动强制对比度(确保至少4.5:1的标准对比度) const highContrastForeground = ensureContrast(foregroundColor, backgroundArgb, 4.5);
注意事项
- 中等对比度无官方固定
contrastLevel值,可根据产品需求在0~1区间内调整,或绑定用户自定义的滑块输入。 - 若使用自定义调色板,需确保
CorePalette实例包含完整的6个调色板数据,可通过fromJSON导入配置。
内容的提问来源于stack exchange,提问作者aknott
相关产品推荐
相关产品推荐

