How to change the background color of pie slice with JavaScript?

时间:2017-08-30 20:28:37

标签: javascript css charts pie-chart

I'm trying to build a pie chart which dynamically change depending the value of range input.

This is what I've done so far: https://codepen.io/anon/pen/wqQLPy

full_name
names_xwalk <- df_with_id %>% 
  mutate(full_name = str_c(name, " ", surname)) %>% 
  count(unique_name, full_name) %>% 
  group_by(unique_name) %>% 
  arrange(desc(n)) %>% 
  slice(1) %>% 
  ungroup() %>% 
  separate(full_name, c("first_name", "last_name")) %>% 
  select(-n)
final <- df_with_id %>% 
  select(-name, -surname) %>% 
  left_join(names_xwalk, by = "unique_name") %>% 
  select(-unique_name)

final

#> # A tibble: 8 x 3
#>   random_value first_name  last_name
#>          <int>      <chr>      <chr>
#> 1            1       Luke  Skywalker
#> 2            2       Luke  Skywalker
#> 3            3       Luke  Skywalker
#> 4            4       Leia     Organa
#> 5            5        Han       Solo
#> 6            6       Leia     Organa
#> 7            7        Ben       Solo
#> 8            8      Lando Calrissian

My question is - how to set a different background color to the slice (area between two lines)?

Example:

Pie chart

1 个答案:

答案 0 :(得分:1)

使用svg这个东西比较好 试试那个

&#13;
&#13;
const $slider = document.querySelector('input[type=range]');
const $currrentValue = document.querySelector('.current-value');
const $circle = document.querySelector('.circle');

$slider.addEventListener('input', handleChange);

function handleChange() {
  
    $currrentValue.textContent = this.value;

    const degrees = this.value;

    $circle.style = 'stroke-dasharray:'+degrees+' 150';
}
&#13;
body {
  text-align: center;
  font-size: 2em;
}

input {
    width: 300px;
    max-width: 80%;
}

input:hover {
  cursor: pointer;
}

.current-value {
    position: relative;
    top: -30px;
    left: -7px;
    font-weight: bold;
}

.pie{
  border-radius: 50%;
}

.pie circle {
  fill: yellow;
  stroke: red;
  stroke-width: 30;
}
&#13;
<p>0 <input type="range" min="0" max="100" value="25"> 100</p>
<p class="current-value">25</p>

<div style="margin:0 auto ;width:100px; height: 100px;">
<svg class="pie" viewBox="0 0 30 30">
<circle r="15" cx="15" cy="15" transform="rotate(45,15,15)" />
  <circle class="circle"  style="stroke-dasharray: 10.5 150;" r="15" cx="15" cy="15" />

</svg>
</div>
&#13;
&#13;
&#13;