用css画立体锥形图

1,392 阅读2分钟

事情是这样的,最近在弄一个项目,关于可视化的(实际上最近其他几篇分享也是同一个项目),里面有一个立体的锥形图,设计稿长这样:

准确来讲,其实这也不算立体的,只是视觉上有立体效果,姑且就认为是立体图吧。

一开始,我是用ecahrts的漏斗图制作的,效果是这样(直接从echarts 官网截的实例图。颜色问题请忽略):

个人觉还行,但领导是在觉得丑,无奈之下,只能选择其他方案。从网上查找相关的资料,并没有发现相关实例可参考,只有highcharts图表库有一个3d的锥形图,但真的很丑,且没办法修改成我所需要的样式,我只好另寻他路了。

在否定了直接切图这个方案后,我开始向社群的大佬们请教,找到了新的方向,通过CSS画出来。

show me the code,这里给出我的方法:

//vue template
<div class="circle">
  <div class="one gh">
    <span class="arc" />
  </div>
  <div class="two gh">
    <span class="ellipse" />
    <span class="arc" />
  </div>
  <div class="three gh">
    <span class="ellipse" />
    <span class="arc" />
  </div>
  <div class="four gh">
    <span class="ellipse" />
    <span class="arc" />
  </div>
</div>

//vue scss
.circle {
    width: 150px;
    height: 100%;
    .gh {
      border-style: solid;
      height: 0;
      margin: 0 auto;
      position: relative;
    }
    .arc {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      height: 8px;
      border-radius: 50%;
    }
    .ellipse {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      height: 4px;
      border-radius: 50%;
      top: -2px;
    }
    .one {
      border-color: transparent transparent #cda01e transparent;
      border-width: 0 12px 20px 12px;
      width: 24px;
      .arc {
        bottom: -24px;
        width: 24px;
        background-color: #cda01e;
      }
    }
    .two {
      border-color: transparent transparent #8540f6 transparent;
      border-width: 10px 12px 30px 12px;
      width: 54px;
      .arc {
        bottom: -34px;
        width: 54px;
        background-color: #8540f6;
      }
      .ellipse {
        width: 30px;
        background-color: #4511a2;
      }
    }
    .three {
      border-color: transparent transparent #4b78f2 transparent;
      border-width: 10px 12px 30px 12px;
      width: 84px;
      .arc {
        bottom: -34px;
        width: 84px;
        background-color: #4b78f2;
      }
      .ellipse {
        width: 60px;
        background-color: #1f4094;
      }
    }
    .four {
      border-color: transparent transparent #28f8c3 transparent;
      border-width: 10px 12px 40px 12px;
      width: 114px;
      .arc {
        bottom: -44px;
        width: 114px;
        background-color: #28f8c3;
      }
      .ellipse {
        height: 6px;
        top: -3px;
        width: 90px;
        background-color: #006384;
      }
    }
  }

简单说明下:因为css可以画三角形,圆形等几何图形,而我要实现的这个图,可以认为是三角形,圆弧,梯形组成,这样一想,好像也没啥问题。我先将图分成了四块,可以看出,每块都有一个主体部分(三角形或梯形)和底部的圆弧(可以认为是椭圆),另外除第一块的锥尖,其余三块还有顶部的视觉阴影效果(椭圆)。

经过排版定位,实际效果如下:

看起来还蛮像的吧,当然如果你有好的实现方式,请指教!