Javascript 如何使用chart.js在甜甜圈图表中添加文本?
如何在甜甜圈图表中呈现文本,我正在使用。首先,感谢您选择chart.js!我正在我当前的一个项目中使用它,我绝对喜欢它——它完美地完成了工作 尽管标签/工具提示还不是库的一部分,但您可能需要查看以下三个拉取请求:Javascript 如何使用chart.js在甜甜圈图表中添加文本?,javascript,chart.js,Javascript,Chart.js,如何在甜甜圈图表中呈现文本,我正在使用。首先,感谢您选择chart.js!我正在我当前的一个项目中使用它,我绝对喜欢它——它完美地完成了工作 尽管标签/工具提示还不是库的一部分,但您可能需要查看以下三个拉取请求: 而且,如前所述,Chart.js使用canvas进行渲染,因此您也可以通过直接与它交互来实现自己的工具提示 希望这有帮助。您必须修改代码,如: 在chart.Doughnut.defaults中 labelFontFamily : "Arial", labelFontStyl
canvas
进行渲染,因此您也可以通过直接与它交互来实现自己的工具提示
希望这有帮助。您必须修改代码,如: 在
chart.Doughnut.defaults中
labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"
然后在函数drawPieSegments
ctx.fillText(数据[0]。值+“%”,宽度/2-20,宽度/2200)代码>
看到这个拉动:
下面是一个实现相同功能的提琴。您还可以将mayankcpdixit的代码粘贴到onAnimationComplete
选项中:
// ...
var myDoughnutChart = new Chart(ctx).Doughnut(data, {
onAnimationComplete: function() {
ctx.fillText(data[0].value + "%", 100 - 20, 100, 200);
}
});
文本将在动画后显示我不想修改chart.js代码来实现这一点,因为使用常规CSS和HTML非常容易。以下是我的解决方案:
HTML:
输出如下所示:
这也在我这边起作用
<div style="width: 100px; height: 100px; float: left; position: relative;">
<div
style="width: 100%; height: 40px; position: absolute; top: 50%; left: 0; margin-top: -20px; line-height:19px; text-align: center; z-index: 999999999999999">
99%<Br />
Total
</div>
<canvas id="chart-area" width="100" height="100" />
</div>
99%
全部的
基于@rap-2-h answer,这里是在chart.js上的圆环图上使用文本的代码,用于类似仪表板的应用。它具有响应选项的动态字体大小
HTML:
这里是示例代码。请尝试调整窗口大小 @rap-2-h和@Ztuons Ch的答案不允许激活showTooltips
选项,但您可以做的是在绘制图表的画布后面创建第二个画布
对象并将其分层
重要的部分是div和canvas对象本身所需的样式,以便它们彼此重叠渲染
var数据=[
{值:100,颜色:“rgba(226151093,1)”,高亮显示:“rgba(226151093,0.75)”,标签:“扇区1”},
{值:100,颜色:“rgba(214113088,1)”,高亮显示:“rgba(214113088,0.75)”,标签:“扇区2”},
{值:100,颜色:“rgba(202097096,1)”,高亮显示:“rgba(202097096,0.75)”,标签:“扇区3”}
]
var options={showTooltips:true};
var合计=0;
对于(i=0;i
这里是上述解决方案的清理和组合示例-响应(尝试调整窗口大小)、支持动画自动对齐、支持工具提示
Chart.types.Doughnut.extend({
名称:“甜甜圈面”,
showTooltip:function(){
this.chart.ctx.save();
Chart.types.Doughnut.prototype.showTooltip.apply(这是参数);
this.chart.ctx.restore();
},
绘图:函数(){
Chart.types.Doughnut.prototype.draw.apply(这是参数);
var width=this.chart.width,
高度=this.chart.height;
变量fontSize=(高度/114).toFixed(2);
this.chart.ctx.font=fontSize+“em Verdana”;
this.chart.ctx.textbrealine=“middle”;
var text=“82%”,
textX=Math.round((width-this.chart.ctx.measureText(text.width)/2),
textY=高度/2;
this.chart.ctx.fillText(text,textX,textY);
}
});
风险值数据=[{
数值:30,
颜色:“F7464A”
}, {
价值:50,
颜色:“E2EAE9”
}, {
数值:100,
颜色:“D4CCC5”
}, {
价值:40,
颜色:“949FB1”
}, {
数值:120,
颜色:“4D5360”
}];
var DoughnuttedSideChart=新图表($('#myChart')[0]。getContext('2d'))。DoughnuttedSide(数据{
回答:对
});代码>
我创建了一个带有7个jQueryUI滑块和ChartJs(内置动态文本)的演示
这是基于Cmyker对Chart.js 2的更新。(作为另一个答案发布,因为我还不能发表评论)
我在Chrome上的文本对齐时遇到了一个问题,因为图例的高度不包括这个,所以它没有在中间正确对齐。通过在计算fontSize和textY时对此进行说明,修复了此问题
我在方法中计算了百分比,而不是一个设定值,因为页面上有多个。假设您的图表只有2个值(否则百分比是多少?第一个是您要显示百分比的值)。我也有一堆其他图表,所以我检查type=doughnut。我只使用doughnut显示百分比,所以它对我有效
文本颜色似乎有点随意,取决于运行的顺序等,因此我在调整文本大小时遇到了一个问题,即文本会改变颜色(在一种情况下在黑色和主颜色之间,在另一种情况下在次颜色和白色之间),因此我“保存”现有填充样式是什么,绘制文本(以主数据的颜色)然后恢复旧的填充样式。(保留旧的填充样式似乎不需要,但您永远不知道。)
var数据={
标签:[“红色”、“蓝色”],
数据集:[
{
数据:[300,50],
背景颜色:[“#FF6384”、“#36A2EB”],
}]
};
Chart.pluginService.register({
绘制前:函数(图表){
变量宽度=chart.chart.width,
高度=chart.chart.height,
ctx=chart.chart.ctx,
type=chart.config.type;
如果(类型=='doughnut')
{
var percent=Math.round((chart.config.data.datasets[0].data[0]*100)/
(chart.config.data.datasets[0]。数据[0]+
chart.config.data.datasets[0].data[1]);
var oldFill=ctx.fillStyle;
变量
.donut-inner {
margin-top: -100px;
margin-bottom: 100px;
}
.donut-inner h5 {
margin-bottom: 5px;
margin-top: 0;
}
.donut-inner span {
font-size: 12px;
}
<div style="width: 100px; height: 100px; float: left; position: relative;">
<div
style="width: 100%; height: 40px; position: absolute; top: 50%; left: 0; margin-top: -20px; line-height:19px; text-align: center; z-index: 999999999999999">
99%<Br />
Total
</div>
<canvas id="chart-area" width="100" height="100" />
</div>
<div>text
<canvas id="chart-area" width="300" height="300" style="border:1px solid"/><div>
var doughnutData = [
{
value: 100,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#CCCCCC",
highlight: "#5AD3D1",
label: "Green"
}
];
$(document).ready(function(){
var ctx = $('#chart-area').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(doughnutData,{
animation:true,
responsive: true,
showTooltips: false,
percentageInnerCutout : 70,
segmentShowStroke : false,
onAnimationComplete: function() {
var canvasWidthvar = $('#chart-area').width();
var canvasHeight = $('#chart-area').height();
//this constant base on canvasHeight / 2.8em
var constant = 114;
var fontsize = (canvasHeight/constant).toFixed(2);
ctx.font=fontsize +"em Verdana";
ctx.textBaseline="middle";
var total = 0;
$.each(doughnutData,function() {
total += parseInt(this.value,10);
});
var tpercentage = ((doughnutData[0].value/total)*100).toFixed(2)+"%";
var textWidth = ctx.measureText(tpercentage).width;
var txtPosx = Math.round((canvasWidthvar - textWidth)/2);
ctx.fillText(tpercentage, txtPosx, canvasHeight/2);
}
});
});
Chart.types.Doughnut.extend({
name: "DoughnutTextInside",
showTooltip: function() {
this.chart.ctx.save();
Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
this.chart.ctx.restore();
},
draw: function() {
Chart.types.Doughnut.prototype.draw.apply(this, arguments);
var width = this.chart.width,
height = this.chart.height;
var fontSize = (height / 140).toFixed(2);
this.chart.ctx.font = fontSize + "em Verdana";
this.chart.ctx.textBaseline = "middle";
var red = $( "#red" ).slider( "value" ),
green = $( "#green" ).slider( "value" ),
blue = $( "#blue" ).slider( "value" ),
yellow = $( "#yellow" ).slider( "value" ),
sienna = $( "#sienna" ).slider( "value" ),
gold = $( "#gold" ).slider( "value" ),
violet = $( "#violet" ).slider( "value" );
var text = (red+green+blue+yellow+sienna+gold+violet) + " minutes";
var textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2);
var textY = height / 2;
this.chart.ctx.fillStyle = '#000000';
this.chart.ctx.fillText(text, textX, textY);
}
});
var ctx = $("#myChart").get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx).DoughnutTextInside(data, {
responsive: false
});
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx,
type = chart.config.type;
if (type == 'doughnut')
{
var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
(chart.config.data.datasets[0].data[0] +
chart.config.data.datasets[0].data[1]));
var oldFill = ctx.fillStyle;
var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);
ctx.restore();
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle"
var text = percent + "%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = (height + chart.chartArea.top) / 2;
ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
ctx.fillText(text, textX, textY);
ctx.fillStyle = oldFill;
ctx.save();
}
}
});
Chart.pluginService.register({
beforeDraw: function(chart) {
if (chart.config.options.elements.center) {
// Get ctx from string
var ctx = chart.chart.ctx;
// Get options from the center object in options
var centerConfig = chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var maxFontSize = centerConfig.maxFontSize || 75;
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
// Start with a base font of 30px
ctx.font = "30px " + fontStyle;
// Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
var minFontSize = centerConfig.minFontSize;
var lineHeight = centerConfig.lineHeight || 25;
var wrapText = false;
if (minFontSize === undefined) {
minFontSize = 20;
}
if (minFontSize && fontSizeToUse < minFontSize) {
fontSizeToUse = minFontSize;
wrapText = true;
}
// Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px " + fontStyle;
ctx.fillStyle = color;
if (!wrapText) {
ctx.fillText(txt, centerX, centerY);
return;
}
var words = txt.split(' ');
var line = '';
var lines = [];
// Break words up into multiple lines if necessary
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > elementWidth && n > 0) {
lines.push(line);
line = words[n] + ' ';
} else {
line = testLine;
}
}
// Move the center up depending on line height and number of lines
centerY -= (lines.length / 2) * lineHeight;
for (var n = 0; n < lines.length; n++) {
ctx.fillText(lines[n], centerX, centerY);
centerY += lineHeight;
}
//Draw text in center
ctx.fillText(line, centerX, centerY);
}
}
});
options: {
elements: {
center: {
text: 'Red is 2/3 the total numbers',
color: '#FF6384', // Default is #000000
fontStyle: 'Arial', // Default is Arial
sidePadding: 20, // Default is 20 (as a percentage)
minFontSize: 20, // Default is 20 (in px), set to false and text will not wrap.
lineHeight: 25 // Default is 25 (in px), used for when text wraps
}
}
}
Chart.pluginService.register({
beforeDraw: function(chart) {
if (chart.canvas.id === 'doghnutChart') {
let width = chart.chart.width,
height = chart.chart.outerRadius * 2,
ctx = chart.chart.ctx;
rewardImg.width = 40;
rewardImg.height = 40;
let imageX = Math.round((width - rewardImg.width) / 2),
imageY = (height - rewardImg.height ) / 2;
ctx.drawImage(rewardImg, imageX, imageY, 40, 40);
ctx.save();
}
}
});
<div class="relative">
<canvas id="myChart"></canvas>
<div class="absolute-center text-center">
<p>Some text</p>
<p>Some text</p>
</div>
</div>
Chart.pluginService.register({
beforeDraw: function(chart) {
if (chart.config.options.elements.center) {
// Get ctx from string
var ctx = chart.chart.ctx;
// Get options from the center object in options
var centerConfig = chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var maxFontSize = centerConfig.maxFontSize || 75;
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
// Start with a base font of 30px
ctx.font = "30px " + fontStyle;
// Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
var minFontSize = centerConfig.minFontSize;
var lineHeight = centerConfig.lineHeight || 25;
var wrapText = false;
if (minFontSize === undefined) {
minFontSize = 20;
}
if (minFontSize && fontSizeToUse < minFontSize) {
fontSizeToUse = minFontSize;
wrapText = true;
}
// Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px " + fontStyle;
ctx.fillStyle = color;
if (!wrapText) {
ctx.fillText(txt, centerX, centerY);
return;
}
var lines = [];
var chunks = txt.split('\n');
for (var m = 0; m < chunks.length; m++) {
var words = chunks[m].split(' ');
var line;
// Break words up into multiple lines if necessary
for (var n = 0; n < words.length; n++) {
var testLine = (n == 0) ? words[n] : line + ' ' + words[n];
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > elementWidth && n > 0) {
lines.push(line);
line = words[n];
} else {
line = testLine;
}
}
lines.push(line);
}
// Move the center up depending on line height and number of lines
centerY -= ((lines.length-1) / 2) * lineHeight;
// All but last line
for (var n = 0; n < lines.length; n++) {
ctx.fillText(lines[n], centerX, centerY);
centerY += lineHeight;
}
}
}
});