我正在使用 Chart.js 来可视化我的数据,如下图所示。
我想在图表中间添加一张照片。
如何在圆环图中间添加照片? 这是我的 JavaScript 代码:
$.ajax({
type: "POST",
url: "/Plant/SunChart",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (jsonData) {
var items = jsonData[0];
var countOfItems = jsonData[1];
var ctx = document.getElementById("sunPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: items,
datasets: [{
data: countOfItems,
backgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
hoverBackgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
options: {
maintainAspectRatio: false,
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
},
legend: {
display: false
},
cutoutPercentage: 80,
},
});
}
});
插件核心 API 提供了一系列可用于执行自定义代码的挂钩。您可以使用
afterDraw
钩子使用 CanvasRenderingContext2D.drawImage()
直接在画布上绘制图像。
请查看下面修改后的代码。
new Chart('myChart', {
type: 'doughnut',
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
var image = new Image();
image.src = 'https://i.stack.imgur.com/S7tJH.png';
imageSize = 40;
ctx.drawImage(image, chart.chart.width / 2 - imageSize / 2, chart.chart.height / 2 - imageSize / 2, imageSize, imageSize);
ctx.restore();
}
}],
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [50, 25, 25],
backgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
hoverBackgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
options: {
maintainAspectRatio: false,
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
},
legend: {
display: false
},
cutoutPercentage: 80,
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>
https://dotnetfiddle.net/jJKo4I
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
归功于 如何使用chart.js在圆环图中添加图像? 和 https://www.c-sharpcorner.com/article/charts-in-asp-net-mvc-using-chart-js/ 和 http://jsfiddle.net/jimrhoskins/Sv87G/
Uminder的回答非常有帮助。添加到将图像放置在中心更新下面的代码
afterDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
var image = new Image();
image.src = 'https://i.stack.imgur.com/S7tJH.png';
imageSize = 40;
const {top, left, width, height} = chart.chartArea;
const x = left + width / 2 - imageSize / 2;
const y = top + height / 2 - imageSize / 2;
ctx.drawImage(image, x , y, imageSize, imageSize);
ctx.restore();
}
官方文档。我希望有人会觉得它有帮助。