Material Design Color Utilities 使用 Material Web 组件生成意想不到的颜色

问题描述 投票:0回答:1

我正在开发一个项目,其中使用 Material Design Color Utilities 包来创建基于原色的动态颜色主题。但是,我注意到生成的颜色并不符合预期。

这是我当前的代码:

import { argbFromHex, hexFromArgb, TonalPalette, themeFromSourceColor, applyTheme, Theme } from "@material/material-color-utilities";

const baseColors = {
  primary: '#000000',
  secondary: '#FCE800',
  tertiary: '#00BFFF',
  error: '#F00F3E',
  neutral: '#6F7B80',
  neutralVariant: '#7B7768'
};

const createTheme = (): Theme => {
  const primaryArgb = argbFromHex(baseColors['primary']);
  const secondaryArgb = argbFromHex(baseColors['secondary']);
  const tertiaryArgb = argbFromHex(baseColors['tertiary']);
  const errorArgb = argbFromHex(baseColors['error']);
  const neutralArgb = argbFromHex(baseColors['neutral']);
  const neutralVariantArgb = argbFromHex(baseColors['neutralVariant']);

  const theme = themeFromSourceColor(primaryArgb);

  return {
    source: primaryArgb,
    schemes: theme.schemes,
    palettes: {
      primary: TonalPalette.fromInt(primaryArgb),
      secondary: TonalPalette.fromInt(secondaryArgb),
      tertiary: TonalPalette.fromInt(tertiaryArgb),
      neutral: TonalPalette.fromInt(neutralArgb),
      neutralVariant: TonalPalette.fromInt(neutralVariantArgb),
      error: TonalPalette.fromInt(errorArgb),
    },
    customColors: [],
  };
};
/*Overwrite mui system colors*/
const applyThemeVars = (root: HTMLElement, isDarkMode: boolean, theme: any) => {
  const style = root.style;
  const colors = isDarkMode ? theme.schemes.dark : theme.schemes.light;
  Object.entries(colors.props).forEach(([key, value]) => {
    const hexColor = hexFromArgb(value as number);
    style.setProperty(`--md-sys-color-${key}`, hexColor);
  });
};

const applyCustomTheme = (isDarkMode: boolean) => {
  const generatedTheme = createTheme();
  applyThemeVars(document.documentElement, isDarkMode, generatedTheme);
  applyTheme(generatedTheme, { target: document.documentElement, dark: isDarkMode });
};

export const ThemeHelper = () => {
  return {
    applyCustomTheme,
  };
};

const themeHelper = ThemeHelper();
export default themeHelper;

我正在使用 themeFromSourceColor 根据原色 (#000000) 生成我的主题。但是,我得到的原色是深紫色 (#984061),而不是黑色 (#000000)。

套餐: https://github.com/material-components/material-web#readme https://github.com/material-foundation/material-color-utilities

问题: 为什么 themeFromSourceColor 生成深紫色而不是黑色?如何确保生成的原色与我指定的颜色完全匹配?

typescript material-ui web-component
1个回答
0
投票

您的问题有多个问题

  • 您使用的是“源颜色”(#000000),而不是“原色” 生成主题
  • 您无法确保生成的原色与您指定的颜色完全匹配,并且不应期待这种情况

回答你的第一个问题:

  1. 经过多次计算库创建了一个TonalPalette 基于源颜色
  2. 然后从调色板色调(50)中选择灯光颜色 主题作为主色
  3. 有关更多详细信息,您可以浏览源代码https://github.com/material-foundation/material-color-utilities/blob/main/typescript/utils/theme_utils.ts#L77
© www.soinside.com 2019 - 2024. All rights reserved.