简体   繁体   中英

How can I animate a pie chart part from 0 to 100% in svg?

I am trying to figure out how to animate a pie chart part from 0 to 100. I can't even draw an arc that has more than 180 degrees. If I try to animate from a 1 degree angle to a 90 degree angle, instead of having a nice transition I'm getting a shape morph.

I'm trying to draw parts of the pie chart with paths like this:

M 100 100 l 0 -50 a 50 50 0 0 0 -20 10 z

My first challenge is calculating the last two numbers, the end point of the arc, and the second challenge is writing an animation that goes from a 1 deg angle to a 360 deg angle.

Any help would be greatly appreciated!

Its worth reading this answer on SO which has info on the dasharray effect which can be useful. That doesn't directly answer the pie question, but may give some ideas. A lot will depend on specifically how you want it animated, to whether these would work for you.

So you could draw a full circle with a string like "M 100, 100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0" which draws 2 arcs.

You could also just do it with a circle. So here's a few bits, and a Snap example alongside it, as you will be using that, and its useful to compare...

<svg width="600" height="425">
    <path d="M 100, 100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0" fill="none" stroke="black" stroke-width="150" stroke-dasharray="0 600 600 0" stroke-dashoffset="1000">
        <animate attributeType="XML" attributeName="stroke-dashoffset" from="0" to="600" dur="2s" repeatCount="1" fill="freeze"/> 
    </path>
    <circle cx="150" cy="350" r="80" fill="none" stroke="red" stroke-width="161" stroke-dasharray="0 600 600 0" stroke-dashoffset="1000" >
        <animate attributeType="XML" attributeName="stroke-dashoffset" from="0" to="600" dur="2s" repeatCount="1" fill="freeze">
        </animate>
    </circle>
</svg>

same last bit with Snap.js

var s = Snap(600,600);

var c = s.circle(150, 150, 80).attr({
    fill: "none",
    stroke: 'red',
    strokeWidth: 161,
    strokeDasharray: "0 600 600 0",
    strokeDashoffset: 1000
});

Snap.animate(0,600, function( value ){ 
       c.attr({ 'strokeDashoffset': value })
},5000 );

Here is a jsfiddle with them all on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM