生成多个不同比率的静态饼图的办法,可以通过上面的那个动画的实现,需要设置动画处于暂停状态,然后设置负的动画延时直接跳转到动画中的任意时间点, 最终实现的代码如下:
<div class="pie" style="animation-delay: -20s"> <span>20</span> </div> <div class="pie" style="animation-delay: -60s"> <span>60</span> </div> .pie{ position: relative; width: 100px; height: 100px; line-height: 100px; border-radius: 50%; background: yellowgreen; background-image: linear-gradient(to right, transparent 50%, #655 0); color: #000; text-align: center; } @keyframes spin { to { transform: rotate(.5turn); } } @keyframes bg { 50% { background: #655; } } .pie::before { content: ''; position: absolute; top: 0; left: 50%; width: 50%; height: 100%; border-radius: 0 100% 100% 0 / 50%; background-color: inherit; transform-origin: left; animation: spin 50s linear infinite, bg 100s step-end infinite; animation-play-state: paused; animation-delay: inherit; } .pie span { position: relative; z-index: 10; }效果如下:
用SVG 解决方案 <svg viewBox="0 0 32 32"> <circle r="16" cx="16" cy="16" /> </svg> svg { width: 100px; height: 100px; transform: rotate(-90deg); background: yellowgreen; border-radius: 50%; } circle { fill: yellowgreen; stroke: #655; stroke-width: 32; stroke-dasharray: 38 100; /* 可得到比率为38%的扇区 */ }让饼图的周长无限接近100,就可以直接把比率的百分比值指定为strokedasharray的长度,不需要做任何计算了。因为周长是2πr,半径就是100/22π ≈ 15.915,最终把这个值取整为16。在SVG的viewBox属性中指定其尺寸,而不再使用width和height属性,这样就可以让它自动适应容器的大小了。
SVG的优点是增加第三种颜色是非常容易的,并且可以用内联样式来指定颜色。
(责任编辑:admin)