chart.js画图

解晟睿
2023-12-01

       最近需要使用chart.js画图来显示数据,发现chart.js的效果很不错,很方便的可以画出柱状图或者饼图,当时需求准备画出一个doughnut图,并实现周围有相应颜色的提示栏,鼠标放置上去会有提示效果出现。

<div>
<canvas id = "canvas"></canvas>
</div>
<div id = "legend"></div>
<script>
var data = [
{
value: 300,
color: "#fdd",
label: "red"
},
{
value: 50,
color: "#435",
label: "yellow"
}
];
var helpers = Chart.helpers;
var ctx = document.getElementById("canvas").getContext("2d");
var myDoughnutChart = new Chart(ctx).Doughnut(
data,{
animateRotate: true
});
var legendHolder = document.getElementById("legend");
legendHolder.innerHTML = myDoughnutChart.generateLegend();
helpers.each(legendHolder.firstChild.childNodes,function(legendNode,index){
var activeSegment = myDoughnutChart.segments[index];
activeSegment.save();
myDoughnutChart.showTooltip([activeSegment]);
activeSegment.restore();
});
helpers.addEvent(legendNode,'click',function(){
var activeSegment1 = myDoughnutChart.segments[index];
alert(activeSegment1.value);
});
});
helpers.addEvent(legendHolder.firstChild,'mouseout',function(){
myDoughnutChart.draw();
});
myDoughnutChart.chart.canvas.parentNode.parentNode.appendChild(legendHolder.firstChild);
</script>


 类似资料: