问题
I need to add images inside bar chart in chart.js.
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
回答1:
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>
来源:https://stackoverflow.com/questions/57787960/add-images-inside-bar-chart-in-chart-js