class ColorTransformer {
_step;
beginColor;
endColor;
colorTransforms;
constructor(beginColor, endColor,_step=100) {
this.beginColor = this.hexToRgb(beginColor.toLocaleLowerCase());
this.endColor = this.hexToRgb(endColor.toLocaleLowerCase());
this._step = _step;
this.colorTransforms = this.createColorTransformList(this.beginColor,this.endColor,this._step);
}
/** 10进制转16进制 */
#tenToSixteen(color_ten) {
return Number(color).toString(16);
}
/** 16进制转10进制 */
#sixteenToTen(color_sixteen) {
return Number.parseInt(color_sixteen, 16)
}
/** 是否rgb格式 */
#isRGB(rgb) {
if(/^#[a-f|A-F|0-9]{6}$/.test(rgb)) return false;
let res = true;
if (typeof rgb !== 'string') return false;
rgb = rgb.replace(/^rgb\(|\)$/g, '').split(',')
rgb.forEach(item => {
if (item < 0 || item > 255) res = false;
})
return res
}
/** rgb转换成数组 */
#rgbToArr(rgb) {
return rgb.replace(/^rgb\(|\)$/g, '').split(',').map(item => Number.parseInt(item))
}
/** rgb转hex */
rgbToHex(rgb) {
if (/^#[a-f|A-F|0-9]{6}$/.test(rgb)) return rgb;
if (typeof rgb === "string") rgb = this.#rgbToArr(rgb);
const [R, G, B] = rgb;
const RR = this.#tenToSixteen(R), GG = this.#tenToSixteen(G), BB = this.#tenToSixteen(B);
return `#${RR}${GG}${BB}`
}
/** hex转rgb */
hexToRgb(hex) {
if (this.#isRGB(hex)) return hex;
hex = hex.replace('#', '');
const RR = hex.slice(0, 2), GG = hex.slice(2, 4), BB = hex.slice(4);
const R = this.#sixteenToTen(RR), G = this.#sixteenToTen(GG), B = this.#sixteenToTen(BB);
return `rgb(${R},${G},${B})`
}
/** 获取颜色转换平滑数组 */
createColorTransformList(beginColor, endColor, step) {
const [bR, bG, bB] = this.#rgbToArr(beginColor), [eR, eG, eB] = this.#rgbToArr(endColor);
const rR = (eR - bR) / step, rG = (eG - bG) / step, rB = (eB - bB) / step;
const colorStepList = [];
for (let i = 0; i < step; i++) {
colorStepList.push(`rgb(${Number.parseInt(rR * i + bR)},${Number.parseInt(rG * i + bG)},${Number.parseInt(rB * i + bB)})`)
}
colorStepList.pop()
return [...colorStepList,this.endColor]
}
}
js实现css的颜色平滑过渡代码
最新推荐文章于 2023-07-12 13:16:30 发布