bixi
Version:
企业级中后台前端解决方案
74 lines (67 loc) • 1.98 kB
text/typescript
import { log } from '@bixi/core/utils';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import tinycolor from 'tinycolor2';
import { IColorMode } from './color-picker.type';
const COLOR_FUN_MAP: NzSafeAny = {
'hex': 'toHexString',
'rgb': 'toRgb',
'rgbString': 'toRgbString',
'hsl': 'toHsl',
'hslString': 'toHslString',
'hsv': 'toHsv',
'hsvString': 'toHsvString'
};
export function convertColor(color: NzSafeAny) {
const colorInstance = tinycolor(color);
const hsl = colorInstance.toHsl();
const hsv = colorInstance.toHsv();
const rgb = colorInstance.toRgb();
const hex = colorInstance.toHex();
const transparent = hex === '000000' && rgb.a === 0;
return {
hsl,
hex: transparent ? 'transparent' : `#${hex}`,
rgb,
hsv
};
}
export function mapColor(color: NzSafeAny, target: IColorMode) {
const colorInstance = tinycolor(color) as NzSafeAny;
if (!COLOR_FUN_MAP[target]) {
log('color-picker', `mode '${target}' not defined`);
return colorInstance.toHexString();
}
return colorInstance[COLOR_FUN_MAP[target]]();
}
const checkboardCache: { [key: string]: string } = {};
function render(c1: string, c2: string, size: number) {
if (typeof document === 'undefined') {
return null;
}
const canvas = document.createElement('canvas');
canvas.width = size * 2;
canvas.height = size * 2;
const ctx = canvas.getContext('2d');
if (!ctx) {
return null;
}
ctx.fillStyle = c1;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = c2;
ctx.fillRect(0, 0, size, size);
ctx.translate(size, size);
ctx.fillRect(0, 0, size, size);
return canvas.toDataURL();
}
export function getCheckboard(c1: string, c2: string, size: number) {
const key = `${c1}-${c2}-${size}`;
if (checkboardCache[key]) {
return checkboardCache[key];
}
const checkboard = render(c1, c2, size);
if (!checkboard) {
return null;
}
checkboardCache[key] = checkboard;
return checkboard;
}