123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- /**
- * 求两个颜色之间的渐变值
- * @param {string} startColor 开始的颜色
- * @param {string} endColor 结束的颜色
- * @param {number} step 颜色等分的份额
- * */
- function colorGradient(startColor = 'rgb(0, 0, 0)', endColor = 'rgb(255, 255, 255)', step = 10) {
- let startRGB = hexToRgb(startColor, false); //转换为rgb数组模式
- let startR = startRGB[0];
- let startG = startRGB[1];
- let startB = startRGB[2];
- let endRGB = hexToRgb(endColor, false);
- let endR = endRGB[0];
- let endG = endRGB[1];
- let endB = endRGB[2];
- let sR = (endR - startR) / step; //总差值
- let sG = (endG - startG) / step;
- let sB = (endB - startB) / step;
- let colorArr = [];
- for (let i = 0; i < step; i++) {
- //计算每一步的hex值
- let hex = rgbToHex('rgb(' + Math.round((sR * i + startR)) + ',' + Math.round((sG * i + startG)) + ',' + Math.round((sB *
- i + startB)) + ')');
- colorArr.push(hex);
- }
- return colorArr;
- }
- // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
- function hexToRgb(sColor, str = true) {
- let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
- sColor = sColor.toLowerCase();
- if (sColor && reg.test(sColor)) {
- if (sColor.length === 4) {
- let sColorNew = "#";
- for (let i = 1; i < 4; i += 1) {
- sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
- }
- sColor = sColorNew;
- }
- //处理六位的颜色值
- let sColorChange = [];
- for (let i = 1; i < 7; i += 2) {
- sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
- }
- if(!str) {
- return sColorChange;
- } else {
- return `rgb(${sColorChange[0]},${sColorChange[1]},${sColorChange[2]})`;
- }
- } else if (/^(rgb|RGB)/.test(sColor)) {
- let arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",")
- return arr.map(val => Number(val));
- } else {
- return sColor;
- }
- };
- // 将rgb表示方式转换为hex表示方式
- function rgbToHex(rgb) {
- let _this = rgb;
- let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
- if (/^(rgb|RGB)/.test(_this)) {
- let aColor = _this.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
- let strHex = "#";
- for (let i = 0; i < aColor.length; i++) {
- let hex = Number(aColor[i]).toString(16);
- hex = String(hex).length == 1 ? 0 + '' + hex : hex; // 保证每个rgb的值为2位
- if (hex === "0") {
- hex += hex;
- }
- strHex += hex;
- }
- if (strHex.length !== 7) {
- strHex = _this;
- }
- return strHex;
- } else if (reg.test(_this)) {
- let aNum = _this.replace(/#/, "").split("");
- if (aNum.length === 6) {
- return _this;
- } else if (aNum.length === 3) {
- let numHex = "#";
- for (let i = 0; i < aNum.length; i += 1) {
- numHex += (aNum[i] + aNum[i]);
- }
- return numHex;
- }
- } else {
- return _this;
- }
- }
- export default {
- colorGradient,
- hexToRgb,
- rgbToHex
- }
|