Chart.js允许通过HTML5的canvas进行图表绘制。这里我们希望绘制一个环形图,点击图上各segment时可以显示自定义的圆形tooltip。
Chart.js支持通过几个变量添加tooltip,它提供一个tooltipTemplate但是却不支持自定义tooltip的HTML!于是决定自行绘制tooltip手动添加上去。
1. 绘制一个tooltip
CSS:
.ft{
background:#bbaabb;
position:absolute;
left:100px;
top:150px;
}
.circle{
width:100px;
height:100px;
border-radius:50px;
font-size:20px;
color:#fff;
line-height:100px;
text-align:center;
background:#aa9966}
HTML:
<div id="t" class="ft circle">$100.23M</div>
2. 通过Chart.js绘制一个环形图
HTML:
<canvas id="myChart" width="390" height="390"></canvas>
var data = [{
value: 30,
color: "#FA797A",
highlight: "#F7464A"
}, {
value: 50,
color: "#E2EAE9",
highlight: "#E1D9D9"
}, {
value: 100,
color: "#D4CCC5",
highlight: "#D2BCB5"
}, {
value: 40,
color: "#949FB1",
highlight: "#928EA1"
}, {
value: 120,
highlight: "#C69CBE",
color: "#C89DCE"
}
]
var options = {
animation: false,
showTooltips: true,
segmentStrokeWidth:2,
percentageInnerCutout:80,
segmentShowStroke : true,
segmentStrokeColor : "#fff",
tooltipTemplate : "",
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
};
//Get the context of the canvas element we want to select
var c = $('#myChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("myChart").getContext("2d");
/*************************************************************************/
myNewChart = new Chart(ct).Doughnut(data, options);
}
3. 每当我点击一个segment的时候,需要自定义的tooltip出现在该segment中心位置。所以需要计算segment中心的坐标
var calc = function(startAngle, endAngle, outerRadius, innerRadius ,x,y ){
var centreAngle = startAngle + ((endAngle - startAngle) / 2);
var rangeFromCentre = (outerRadius - innerRadius) / 2 + innerRadius;
return {
x : x + (Math.cos(centreAngle) * rangeFromCentre),
y : y + (Math.sin(centreAngle) * rangeFromCentre)
};
}
var activePoints = myNewChart.getSegmentsAtEvent(e);
var chart = $("#myChart");
var chartCenterX = chart.position().left + chart.width()/2;
var chartCenterY = chart.position().top + chart.height()/2;
var arc = activePoints[0];
var arcCenter = calc(arc.startAngle, arc.endAngle, arc.outerRadius, arc.innerRadius, chartCenterX, chartCenterY);
var arcCenterX = arcCenter.x;
var arcCenterY = arcCenter.y;
4. 最后设置只有当在任意segment上点击的时候才出现tooltip
HTML: 将tooltip改为初始不可见
<div id="t" class="ft circle" style="display:none" >$100.23M</div>
$(".ft").css({"left": arcCenterX-$("#t").width()/2, "top":arcCenterY-$("#t").height()/2, "display":"block"});
$(".ft").text("$"+arc.value+"M");
$(".ft").show();