fenzhi-utils
Version:
分值前端项目的js函数库
66 lines (64 loc) • 1.78 kB
JavaScript
// convert #hex notation to rgb array
var parseColor = function (hexStr) {
return hexStr.length === 4
? hexStr
.substr(1)
.split('')
.map(function (s) {
return 0x11 * parseInt(s, 16);
})
: [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(
function (s) {
return parseInt(s, 16);
}
);
};
var pad = function (s) {
return s.length === 1 ? '0' + s : s;
};
/**
* 渐变色数组
* @param {string} start 开始颜色(16进制)
* @param {string} end 结束颜色(16进制)
* @param {number} steps 分解次数
* @param {number} gamma 透明度
* @returns {array} 颜色的渐变色数组
*/
/**
CustomGradientColors('#00ff00', '#ff0000', 0); // []
CustomGradientColors('#00ff00', '#ff0000', 1); // ['#00ff00']
CustomGradientColors('#00ff00', '#ff0000', 4); // ['#00ff00', '#55aa00', '#aa5500', '#ff0000']
CustomGradientColors('#000', '#fff', 3, 2.2); // ['#000000', '#bababa', '#ffffff']
*/
export function CustomGradientColors(start, end, steps, gamma) {
if (steps === 0) {
return [];
} else if (steps === 1) {
return [start];
}
var i,
j,
ms,
me,
output = [],
so = [];
gamma = gamma || 1;
var normalize = function (channel) {
return Math.pow(channel / 255, gamma);
};
start = parseColor(start).map(normalize);
end = parseColor(end).map(normalize);
for (i = 0; i < steps; i++) {
ms = i / (steps - 1);
me = 1 - ms;
for (j = 0; j < 3; j++) {
so[j] = pad(
Math.round(
Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255
).toString(16)
);
}
output.push('#' + so.join(''));
}
return output;
}