Tiffany
Tiffany

Reputation: 239

How to change svg pie chart slices to begin at the top and make clockwise animation dynamically with jquery

I want to make a pie chart with animation, and here is my code.

My problems are:

  1. How to make the chart start from the top (12 O’clock position) without rotating <svg>?
  2. I am going to create pie slices with JQuery. How to set css @keyframes stroke-dasharray dynamically with JQuery?

Thanks!

@keyframes animate_p1 {
  to { stroke-dasharray: 78.5 314; } /* 314 ÷ 4 = 78.5 */
}
#bg {
  fill: #ddd;
}
#p1 {
  stroke-dasharray: 0 314; /* 2π × 50 ≈ 314 */
  stroke-dashoffset: 0;
  animation: animate_p1 1s linear forwards;
}
<svg width="200" height="200">
  <circle id="bg" r="100" cx="100" cy="100" />
  <circle id="p1" r="50" cx="100" cy="100" stroke="yellowgreen" stroke-width="100" fill="none" />
</svg>

Upvotes: 1

Views: 876

Answers (1)

enxaneta
enxaneta

Reputation: 33024

One easy solution would be rotating the SVG element. Another solution would be using a path instead of the second circle.

If you take a look at the path you can see that it begins at M100,50 which is at the top where you need to begin. Next are coning 2 arcs drown in the order you need the animation to happen: first the right one: A50,50 0 0 1 100,150 next the left one:A50,50 0 0 1 100,50.

I hope it helps.

@keyframes animate_p1 {
  to { stroke-dasharray: 78.5 314; } /* 314 ÷ 4 = 78.5 */
}
#bg {
  fill: #ddd;
}
#p1 {
  stroke-dasharray: 0 314; /* 2π × 50 ≈ 314 */
  stroke-dashoffset: 0;
  animation: animate_p1 1s linear forwards;
}

svg{border:1px solid}
<svg width="200" height="200">
  <circle id="bg" r="100" cx="100" cy="100" />
  
  
  
  <path d="M100,50A50,50 0 0 1 100,150A50,50 0 0 1 100,50" id="p1" r="50" cx="100" cy="100" stroke="yellowgreen" stroke-width="100" fill="none" />
</svg>

Upvotes: 2

Related Questions