JavaScript 实现方块间隔渐变进度条

效果

在这里插入图片描述

注意

每个方块的高度和方块的间隔值需要开发者自己通过css实现,方法只会返回每个方块的宽度和渐变色颜色值

/**
 * 计算方块渐变进度条
 * @param {*} value 占比值  (0-100)
 * @param {*} option 配置信息 
 * @returns 返回 每个方块的宽度和渐变颜色值
 */
computedLinearGradientColorPosition(value, option) {
     option = Object.assign(
         {
             width: 4,//每个方块的宽度
             diff: 2,//每个方块间的间隔
             containerWidth: 474,//进度条容器的宽度(不包含内边距边框)
             color: [
                 [0, 247, 255, 0],
                 [233, 194, 112, 1]
             ]//渐变的颜色
         },
         option || {}
     );

     // 计算颜色值
     function computedColor(t) {
         let r = (
             option.color[0][0] * (1 - t) +
             option.color[1][0] * t
         ).toFixed(0);
         let g = (
             option.color[0][1] * (1 - t) +
             option.color[1][1] * t
         ).toFixed(0);
         let b = (
             option.color[0][2] * (1 - t) +
             option.color[1][2] * t
         ).toFixed(0);

         let startOp =
             option.color[0][3] == undefined ? 1 : option.color[0][3];
         let endOp =
             option.color[1][3] == undefined ? 1 : option.color[1][3];

         let opDiff = (option.color[1][3] || 1) - (option.color[0][3] || 1);

         let o = startOp == 1 && endOp == 1 ? 1 : (endOp - startOp) * t;
         return `rgba(${r},${g},${b},${o})`;
     }

     const result = [];

     const _itemWidth = option.width + option.diff;

     const width = option.containerWidth * (value / 100);

     const maxNumber = Math.ceil(width / _itemWidth),
         minNumber = Math.floor(width / _itemWidth);

     const lastItemWidth =
         (Number((width / _itemWidth).toFixed(2)) - minNumber) *
         option.width;

     const _width = minNumber * option.width + lastItemWidth;

     for (
         let index = 0,
             allNumber =
                 maxNumber - minNumber == 0 ? minNumber + 1 : maxNumber;
         index < allNumber;
         index++
     ) {
         let isLastItem = index == allNumber - 1;

         let startColor, endColor;
         //填充块
         if (isLastItem) {
             startColor = computedColor((minNumber * option.width) / _width);
             endColor = computedColor(1);
         } else {
             startColor = computedColor((index * option.width) / _width);
             endColor = computedColor(((index + 1) * option.width) / _width);
         }

         const _o = {
             width: !isLastItem ? option.width : lastItemWidth,
             color: `linear-gradient(270deg, ${startColor} 0%, ${endColor} 100%)`
         };

         result.push(_o);
     }
     return result;
 }

你可能感兴趣的:(SOLUTION,javascript)