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

Chart.js Y轴图片未随数据排序同步更新问题求助

问题:Chart.js Y轴图片排序后未同步更新

我在Chart.js的Y轴上展示了一些图片,但对数据排序后,图片没有跟着同步排序。

自定义插件代码

const flagImagePlugin = {
      id: 'flagImagePlugin',
      beforeDatasetsDraw: (chart: any, args: any, pluginOptions: any) => {
        const ctx = chart.ctx;
        const yAxis = chart.scales.y;
    
        yAxis.ticks.forEach((tick: any, index: number) => {
          const img = loadedImages[index];
          const y = yAxis.getPixelForTick(index);
    
          var height = 50;
          var gap = 5; // Adjust this value for the desired gap
          var xOffset = 8; // Adjust this value to move the images to the left
    
          // Calculate the width based on the aspect ratio
          const aspectRatio = img.height / img.width;
          const width = height / aspectRatio;
    
          this.flagWidth = width;
    
          // Draw rounded rectangle as a clipping mask
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(yAxis.right - width + gap - xOffset, y - height / 2);
          ctx.arcTo(
            yAxis.right - xOffset,
            y - height / 2,
            yAxis.right - xOffset,
            y - height / 2 + 5,
            5
          ); // top-right
          ctx.arcTo(
            yAxis.right - xOffset,
            y + height / 2,
            yAxis.right - width + gap - xOffset,
            y + height / 2,
            5
          ); // bottom-right
          ctx.arcTo(
            yAxis.right - width + gap - xOffset,
            y + height / 2,
            yAxis.right - width + gap - xOffset,
            y - height / 2 + 5,
            5
          ); // bottom-left
          ctx.arcTo(
            yAxis.right - width + gap - xOffset,
            y - height / 2,
            yAxis.right - xOffset,
            y - height / 2,
            5
          ); // top-left
          ctx.closePath();
          ctx.clip();
    
          // Draw the image
          ctx.drawImage(
            img,
            yAxis.right - width + gap - xOffset, // Adjust x-coordinate for the new width
            y - height / 2, // Adjust y-coordinate to center the image
            width, // Use calculated width
            height // Fixed height
          );
    
          // Restore canvas state to remove clipping
          ctx.restore();
        });
      },
    };

图表初始化代码

this.winrateChart = new Chart('winrateChart', {
  type: 'bar',
  data: chartData,
  options: chartOptions,
  plugins: [ChartDataLabels, flagImagePlugin],
});

尝试过的无效更新代码

// Update the chart with the modified data and labels
this.winrateChart.update();
  
// Additionally, we need to trigger the plugin's beforeDraw function again
// to ensure that the flag images are updated
if (this.winrateChart.options.plugins) {
  const plugins = this.winrateChart.options.plugins;

  var flagImagePlugin = plugins.find((plugin: any) => plugin.id === 'flagImagePlugin');

  if (flagImagePlugin) {
    // flagImagePlugin.beforeDraw(this.winrateChart);
    flagImagePlugin.Draw(this.winrateChart);
    console.log('here');
  } else {
    console.log('why here')
  }
}

解决方案

核心问题

插件直接通过tick的索引index获取loadedImages[index],排序后Y轴刻度的顺序改变,但图片和索引的绑定关系没有同步更新,导致图片和对应刻度错位。

修复步骤

  1. 建立标签与图片的映射关系
    不要用索引绑定图片,而是让每个图片和对应的Y轴标签关联,比如构建一个映射对象:

    // 假设chartData.labels是原标签数组,loadedImages是对应图片数组
    const labelToImage = {};
    chartData.labels.forEach((label, idx) => {
      labelToImage[label] = loadedImages[idx];
    });
    
  2. 修改插件逻辑,通过标签取图片
    把插件中通过索引取图片的逻辑改成通过当前刻度的标签从映射中获取:

    const flagImagePlugin = {
      id: 'flagImagePlugin',
      beforeDatasetsDraw: (chart: any, args: any, pluginOptions: any) => {
        const ctx = chart.ctx;
        const yAxis = chart.scales.y;
        // 从插件配置中获取标签-图片映射
        const labelToImage = pluginOptions.labelToImage;
    
        yAxis.ticks.forEach((tick: any, index: number) => {
          // 用当前刻度的标签获取对应图片
          const img = labelToImage[tick.label];
          if (!img) return; // 无对应图片则跳过
          const y = yAxis.getPixelForTick(index);
    
          const height = 50;
          const gap = 5;
          const xOffset = 8;
    
          const aspectRatio = img.height / img.width;
          const width = height / aspectRatio;
    
          this.flagWidth = width;
    
          // 以下绘制逻辑保持不变
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(yAxis.right - width + gap - xOffset, y - height / 2);
          ctx.arcTo(
            yAxis.right - xOffset,
            y - height / 2,
            yAxis.right - xOffset,
            y - height / 2 + 5,
            5
          );
          ctx.arcTo(
            yAxis.right - xOffset,
            y + height / 2,
            yAxis.right - width + gap - xOffset,
            y + height / 2,
            5
          );
          ctx.arcTo(
            yAxis.right - width + gap - xOffset,
            y + height / 2,
            yAxis.right - width + gap - xOffset,
            y - height / 2 + 5,
            5
          );
          ctx.arcTo(
            yAxis.right - width + gap - xOffset,
            y - height / 2,
            yAxis.right - xOffset,
            y - height / 2,
            5
          );
          ctx.closePath();
          ctx.clip();
    
          ctx.drawImage(
            img,
            yAxis.right - width + gap - xOffset,
            y - height / 2,
            width,
            height
          );
    
          ctx.restore();
        });
      },
    };
    
  3. 初始化图表时传入映射配置
    把标签-图片映射作为插件选项传入:

    this.winrateChart = new Chart('winrateChart', {
      type: 'bar',
      data: chartData,
      options: chartOptions,
      plugins: [
        ChartDataLabels,
        {
          ...flagImagePlugin,
          options: { labelToImage } // 传入映射对象
        }
      ],
    });
    
  4. 排序后正确更新图表
    排序时只需要更新chartData的labels和数据集,然后调用update()即可,插件会自动根据新的刻度标签匹配对应图片:

    // 示例:按第一个数据集的值降序排序
    const sortedItems = chartData.labels.map((label, idx) => ({
      label,
      value: chartData.datasets[0].data[idx]
    })).sort((a, b) => b.value - a.value);
    
    // 更新labels和数据集
    chartData.labels = sortedItems.map(item => item.label);
    chartData.datasets[0].data = sortedItems.map(item => item.value);
    
    // 触发图表更新
    this.winrateChart.update();
    

内容的提问来源于stack exchange,提问作者Gustavo Baiocchi Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:35:20