You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript饼图切片:实现按百分比从中心部分填充颜色

解决方案

要实现从圆心开始按百分比填充饼图切片的效果,核心是计算每个切片的填充半径(原半径 × 对应百分比),然后只绘制该半径范围内的扇形区域。以下是修改后的完整实现:

完整代码示例

<canvas id="pieChart" width="400" height="400"></canvas>
const ariSizes = [120, 100, 140];
const arsColors = ["#FFDAB9", "#E6E6FA", "#E0FFFF"];
const ariFillPercent = [22, 32, 55];

// 角度转弧度工具函数
const handleDegreesToRadians = (degrees) => {
  return degrees * Math.PI / 180;
};

// 计算数组前N项和的工具函数(用于确定切片起始角度)
const handleSumTo = (arr, index) => {
  let sum = 0;
  for (let i = 0; i < index; i++) {
    sum += arr[i];
  }
  return sum;
};

// 修改后的切片绘制函数
const handleDrawSegment = (cnv, ctx, iNdx) => {
  ctx.save();
  const centerX = Math.floor(cnv.width / 2);
  const centerY = Math.floor(cnv.height / 2);
  const radius = Math.floor(cnv.width / 2);
  
  // 关键:计算当前切片的填充半径(按百分比缩放)
  const fillRadius = radius * (ariFillPercent[iNdx] / 100);

  const startingAngle = handleDegreesToRadians(handleSumTo(ariSizes, iNdx));
  const arcSize = handleDegreesToRadians(ariSizes[iNdx]);
  const endingAngle = startingAngle + arcSize;

  // 绘制仅填充到指定半径的扇形
  ctx.beginPath();
  ctx.moveTo(centerX, centerY);
  ctx.arc(centerX, centerY, fillRadius, startingAngle, endingAngle, false);
  ctx.closePath();
  ctx.fillStyle = arsColors[iNdx];
  ctx.fill();

  ctx.restore();
};

// 饼图初始化函数
const initPieChart = () => {
  const cnv = document.getElementById('pieChart');
  const ctx = cnv.getContext('2d');
  const centerX = Math.floor(cnv.width / 2);
  const centerY = Math.floor(cnv.height / 2);
  const radius = Math.floor(cnv.width / 2);

  // 先绘制整个饼图的背景(这里用白色,可根据需求调整)
  ctx.fillStyle = '#FFFFFF';
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.fill();

  // 遍历绘制每个切片的填充部分
  for (let i = 0; i < ariSizes.length; i++) {
    handleDrawSegment(cnv, ctx, i);
  }
};

// 启动绘制
initPieChart();

关键修改说明

  1. 填充半径计算:新增fillRadius变量,通过原半径乘以ariFillPercent对应的百分比(转为小数),得到每个切片需要填充的半径长度。
  2. 扇形路径调整:绘制路径时不再使用原半径,而是使用计算出的fillRadius,这样只会填充从圆心到该半径范围内的扇形区域。
  3. 背景层绘制:先绘制一个完整的白色背景饼图,确保未填充的区域显示为空白(可根据需求修改背景色)。

内容的提问来源于stack exchange,提问作者Brian Oh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 23:27:01