CSS3 simple donut chart

前端 未结 5 1734
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 20:17

What I\'m trying to do is create a simple donut chart. I\'m currently using CSS(3) only but I don\'t know if it\'s possible without javascript.

What I have so far:

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 20:59

    This answer is only possible because of Turnip's answer, but I made a few significant changes, and I'll explain how it works as well:

    .donutContainer {
        position: relative;
        float: left;
    }
    
    .donutContainer h2 {
        text-align:center;
        position: absolute;
        line-height: 125px;
        width: 100%;
    }
    
    svg {
        transform: rotate(-90deg);
    }
    
    .donut {
      stroke-dasharray: 440;
      -webkit-animation: donut 1s ease-out forwards;
      animation: donut 1s ease-out forwards;
    }
    
    @-webkit-keyframes donut {
      from {
        stroke-dashoffset: 440;
      }
    }
    
    @keyframes donut {
      from {
        stroke-dashoffset: 440;
      }
    }

    donut

    Layer 1

    donut 2

    Layer 1

    Because the animation uses from instead of to to create the animation, browsers that don't support the animation will show the donut chart complete, instead of not at all. This also makes it possible to change the colored in portion of the donut chart with just inline CSS, and the same single CSS animation can work for any number of donut charts.

    An explaination for the svg stuff:

    stroke-dasharray: In this case, basically the total circumference of the circle.

    stroke-dashoffset: the portion of the circle that is colored in. Zero (0) means all colored in (100%), 440 (or whatever you set the circumference) for none of it colored in (0%)

    Attributes on the circle element:

    r: radius of the circle

    cx: "center X". the center of the circle (X coordinate from bottom left of svg element)

    cy: "center Y". the center of the circle (Y coordinate from bottom left of svg element)

    stroke-width: width of the stroke that will draw the donut

    stroke: color of the donut

提交回复
热议问题