Created
February 23, 2023 17:21
-
-
Save tcdw/16299eefdc77fffc0e4df6aaa14f2dde to your computer and use it in GitHub Desktop.
依赖浏览器 API 的颜色处理函数……?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function cssColorToRGB(color: string) { | |
| // 在浏览器创建一个看不见的元素,把随便什么值喂给它(只要是合法的 CSS 颜色表记就行) | |
| const el = document.createElement("div"); | |
| el.style.color = color; | |
| // 然后再读取它就变成 rgb 或 rgba 开头的标准值了 | |
| const matchRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/; | |
| const matchResult = matchRegex.exec(el.style.color); | |
| if (!matchResult) { | |
| return null; | |
| } | |
| return [Number(matchResult[1]), Number(matchResult[2]), Number(matchResult[3]), Number(matchResult[4] ?? 1)]; | |
| } | |
| export function mixColor(to: string, from: string, amount: number) { | |
| const fromColor = cssColorToRGB(from); | |
| const toColor = cssColorToRGB(to); | |
| if (!fromColor || !toColor) { | |
| throw new Error("Both color must be valid CSS color"); | |
| } | |
| const calcR = fromColor[0] + (toColor[0] - fromColor[0]) * amount; | |
| const calcG = fromColor[1] + (toColor[1] - fromColor[1]) * amount; | |
| const calcB = fromColor[2] + (toColor[2] - fromColor[2]) * amount; | |
| const calcA = fromColor[3] + (toColor[3] - fromColor[3]) * amount; | |
| return [calcR, calcG, calcB, calcA]; | |
| } | |
| export function assembleColor(color: Array<string | number>) { | |
| return `rgba(${color.join(", ")})`; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment