首页 > 解决方案 > 计算 SVG 饼图的百分比

问题描述

我知道那里有图表库,但我希望自己动手创建自己的自定义库。

我从另一个 那里找到了一些工作,他从 javascript 中的数组创建了一个饼图,除了他是基于百分比的。

我一直在尝试对其进行返工,以便:

  1. 从数组中获取您的值
  2. 除以数组中的总数
  3. 使用该百分比作为面积

正如您在运行以下命令时所看到的,除非您预先计算了百分比,否则它不会根据数据形成一个完整的圆圈。

我的目标是将所有替换为percent: xvalue: y以便您可以使用原始值:

const slices = [
  { value: 1024 },
  { value: 5684 },
  { value: 125  },
];

let sum = slices.reduce(function (a, b) {
  return a + b.value
}, 0);

然后在循环中,您可以使用slice.value / sum饼图的百分比。只是它似乎不像原来的百分比值那样工作。

// variables
const svgEl = document.querySelector('svg');
const slices = [
  { percent: 0.1, color: 'red' },
  { percent: 0.1, color: 'blue' },
  { percent: 0.1, color: 'green' },
];
let cumulativePercent = 0;

// coordinates
function getCoordinatesForPercent(percent) {
  const x = Math.cos(2 * Math.PI * percent);
  const y = Math.sin(2 * Math.PI * percent);
  return [x, y];
}

// loop
slices.forEach(slice => {
  // destructuring assignment sets the two variables at once
  const [startX, startY] = getCoordinatesForPercent(cumulativePercent);
  
  // each slice starts where the last slice ended, so keep a cumulative percent
  cumulativePercent += slice.percent;
    
  const [endX, endY] = getCoordinatesForPercent(cumulativePercent);

  // if the slice is more than 50%, take the large arc (the long way around)
  const largeArcFlag = slice.percent > 0.5 ? 1 : 0;

    // create an array and join it just for code readability
  const pathData = [
    `M ${startX} ${startY}`, // Move
    `A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`, // Arc
    `L 0 0`, // Line
  ].join(' ');

  // create a <path> and append it to the <svg> element
  const pathEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  pathEl.setAttribute('d', pathData);
  pathEl.setAttribute('fill', slice.color);
  svgEl.appendChild(pathEl);
});
svg {
  height: 200px;
}
<svg viewBox="-1 -1 2 2" style="transform: rotate(-90deg);fill:black;"></svg>

标签: javascripthtmlcsssvg

解决方案


您不必计算任何百分比(除非您想要百分比值)

让 SVG 完成这项工作pathLength

切片值:blue:10 , gold:20 , red:30使得:pathLength="60"

你只需要计算stroke-dasharray 差距(第二个值= 60 - value
stroke-dashoffset累积值:10、30、60

更高级的使用在:https ://pie-meister.github.io

<style>
  svg {
    width:180px;
  }
</style>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <path stroke-dasharray="10 50" stroke-dashoffset="10" stroke="blue" 
        pathLength="60" 
        stroke-width="50" d="M75 50a1 1 90 10-50 0a1 1 90 10 50 0" fill="none"></path>
        
  <path stroke-dasharray="20 40" stroke-dashoffset="30" stroke="gold" 
        pathLength="60" 
        stroke-width="50" d="M75 50a1 1 90 10-50 0a1 1 90 10 50 0" fill="none"></path>
        
  <path stroke-dasharray="30 30" stroke-dashoffset="60" stroke="red" 
        pathLength="60" 
        stroke-width="50" d="M75 50a1 1 90 10-50 0a1 1 90 10 50 0" fill="none"></path>
</svg>


推荐阅读