在chart.js中的条形图中添加图像 [英] Add images inside bar chart in chart.js

查看:111
本文介绍了在chart.js中的条形图中添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在chart.js的条形图中添加图像。

I need to add images inside bar chart in chart.js.

所有可用的解决方案都使用pointStyle属性处理折线图点。
找不到Barcharts的示例,也没有官方文档提供解决方案。
我检查了插件,但都找不到解决方案。

All available solutions deal with line chart points with pointStyle property. Couldn't find an example for Barcharts nor the official documentation offer solutions. I checked the plugins but couldn't find a solution their either.

var imageExample = new Image();
cloud.src = 'imageurl.png';

Chart.pluginService.register({
    afterUpdate: function (chart) {
        console.log(chart.config.data.datasets[0]);                
        chart.config.data.datasets[0]._meta[0].data[0]._model.pointStyle = imageExample;
    }
});

示例结果应如下所示:输出

An example result should look something like this: output

推荐答案

您可以使用 chartjs-plugin-labels 可以在单个栏中添加图像。

You can use chartjs-plugin-labels to add images inside individual bars.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C'],
    datasets: [{
      label: 'My First Dataset',
      data: [30, 59, 80],
      fill: false,
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
      labels: {
        render: 'image',
        textMargin: -30,
        images: [
          {
            src: 'https://i.stack.imgur.com/9EMtU.png',
            width: 20,
            height: 20
          }, 
          null, 
          {
            src: 'https://i.stack.imgur.com/9EMtU.png',
            width: 20,
            height: 20
          }
        ]
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

canvas {
  max-width: 300px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart" width="10" height="5"></canvas>

这篇关于在chart.js中的条形图中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆