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

求助:如何在Chart.js饼图中仅为指定扇区添加外侧彩色边框

Fixing Custom Outer Borders for Specific Pie Chart Slices in Chart.js

Got it, let's tackle this pie chart border issue! The core problem here is that Chart.js doesn't natively support different border colors for inner slice separators vs outer slice edges. But with a quick custom plugin, we can exactly achieve what you want: white inner separators between all slices, and custom colored outer borders only for your target slices (red and black in your case).

Here's the Modified Working Code

$(document).ready(function () { 
  var ctx = document.getElementById("chartjs-1").getContext("2d"); 
  var chart = new Chart(ctx, { 
    type: "pie", 
    data: { 
      labels: ["Green", "Blue", "Gray", "Purple"], 
      datasets: [ 
        { 
          backgroundColor: ["#F1F1F1", "#F1F1F1", "#F1F1F1", "#F1F1F1"], 
          hoverBackgroundColor: ["#F1F1F1", "#F1F1F1", "#F1F1F1", "#F1F1F1"], 
          borderColor: ["white", "white", "white", "white"], // Inner separators stay white
          data: [12, 19, 3, 17], 
          borderWidth: 5,
          borderAlign: 'center' // Ensures borders draw between slices (inner separators)
        }, 
      ], 
    }, 
    options: { 
      legend: { 
        display: false, 
      }, 
      legendCallback: function (chart) { 
        console.log(chart.data); 
        var text = []; 
        text.push("<ul>"); 
        for (var i = 0; i < chart.data.datasets[0].data.length; i++) { 
          text.push("<li>"); 
          // Use the target color for legend instead of dataset borderColor now
          const targetColors = ['#FF0000', '#000000', '#F2994A', '#56CCF2'];
          text.push( 
            '<span style="background-color:' + targetColors[i] + '">' + chart.data.datasets[0].data[i] + "</span>" 
          ); 
          if (chart.data.labels[i]) { 
            text.push(chart.data.labels[i]); 
          } 
          text.push("</li>"); 
        } 
        text.push("</ul>"); 
        return text.join(""); 
      }, 
    },
    plugins: [{
      afterDraw: function(chart) {
        const ctx = chart.ctx;
        const chartArea = chart.chartArea;
        const centerX = (chartArea.left + chartArea.right) / 2;
        const centerY = (chartArea.top + chartArea.bottom) / 2;
        // Get the outer radius of the pie slices
        const outerRadius = chart.getDatasetMeta(0).data[0].outerRadius;
        // Define your target slices with their index and desired border color
        const targetSectors = [
          {index: 0, color: '#FF0000'},
          {index: 1, color: '#000000'}
        ];

        targetSectors.forEach(sector => {
          const arc = chart.getDatasetMeta(0).data[sector.index];
          // Draw the custom outer border
          ctx.save();
          ctx.beginPath();
          ctx.strokeStyle = sector.color;
          ctx.lineWidth = 5; // Match your original border width
          // Draw arc just outside the pie slice (add half line width to avoid overlap)
          ctx.arc(centerX, centerY, outerRadius + ctx.lineWidth/2, arc.startAngle, arc.endAngle);
          ctx.stroke();
          ctx.restore();
        });
      }
    }]
  }); 
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> 
<canvas id="chartjs-1"></canvas>

Key Changes Explained

  1. Inner Separators Setup:

    • Set borderColor for all slices to white and borderAlign: 'center' — this ensures the lines between slices are always white, which solves your "internal border" requirement.
  2. Custom Outer Border Plugin:

    • We added an afterDraw plugin hook that runs after Chart.js renders the pie chart.
    • For each target slice (index 0 and 1 in your case), we draw an arc just outside the slice's outer edge using the desired color. This creates the custom outer border without affecting the inner separators.
  3. Legend Adjustment:

    • Updated the legendCallback to use your original target colors instead of the dataset's white border color, so the legend still shows the correct colors for each slice.

This approach keeps your inner slice borders white while adding custom colored outer borders only to the slices you specify.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:57:37