colorValidation
颜色值验证和范围限制工具函数集合,提供 RGB、HSL、Alpha 等颜色值的验证和自动修正功能。
函数签名
typescript
// 值修正函数(Clamp)
function clampRgbValue(value: number): number
function clampHueValue(value: number): number
function clampPercentageValue(value: number): number
function clampAlphaValue(value: number): number
// 验证函数
function isValidRgbValue(value: number): boolean
function isValidHueValue(value: number): boolean
function isValidPercentageValue(value: number): boolean
function isValidAlphaValue(value: number): boolean
function isValidRgbColor(rgb: RgbColor): boolean
function isValidHslColor(hsl: HslColor): boolean
interface RgbColor {
r: number // 0-255
g: number // 0-255
b: number // 0-255
a?: number // 0-1
}
interface HslColor {
h: number // 0-360
s: number // 0-100
l: number // 0-100
a?: number // 0-1
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
value | number | 是 | 要验证或修正的数值 |
rgb | RgbColor | 是(仅 isValidRgbColor) | RGB 颜色对象 |
hsl | HslColor | 是(仅 isValidHslColor) | HSL 颜色对象 |
返回值
Clamp 函数
| 类型 | 说明 |
|---|---|
number | 修正后的数值,限制在有效范围内 |
验证函数
| 类型 | 说明 |
|---|---|
boolean | true 表示有效,false 表示无效 |
工作原理
Clamp 函数(值修正)
将超出范围的值修正到有效范围内:
clampRgbValue(value):
- 限制范围:0-255
- 四舍五入到整数
Math.round(Math.max(0, Math.min(255, value)))
clampHueValue(value):
- 限制范围:0-360
- 四舍五入到整数
Math.round(Math.max(0, Math.min(360, value)))
clampPercentageValue(value):
- 限制范围:0-100
- 四舍五入到整数
Math.round(Math.max(0, Math.min(100, value)))
clampAlphaValue(value):
- 限制范围:0-1
- 不进行四舍五入,保留精度
Math.max(0, Math.min(1, value))
验证函数
检查值是否在有效范围内,不修改值:
- isValidRgbValue: 检查是否在 0-255 范围内
- isValidHueValue: 检查是否在 0-360 范围内
- isValidPercentageValue: 检查是否在 0-100 范围内
- isValidAlphaValue: 检查是否在 0-1 范围内
- isValidRgbColor: 检查 RGB 对象的所有属性是否有效
- isValidHslColor: 检查 HSL 对象的所有属性是否有效