可拖动饼图是一个JavaScript/jQuery插件,可帮助开发人员使用HTML5画布生成可拖动、交互式、移动友好的饼图。
它允许用户通过简单地使用鼠标拖动和触摸手势来改变每个片段的比例,这为数据可视化提供了独特的交互式体验。
1.要开始使用可拖动饼图,请将以下JavaScript文件加载到文档中。
<!-- Vanilla JS --> <script src="/path/to/draggable-piechart.js"></script> <!-- jQuery --> <script src="/path/to/cdn/jquery.min.js"></script> <script src="/path/to/cdn/draggable-piechart-jquery.js"></script>
2.创建一个空帆布
元素来放置饼图。
<canvas id="piechart" width="300" height="300"> Your browser is too old! </canvas>
3.初始化一个新的DraggablePiechart实例,然后以对象数组的形式提供数据,如下所示:
var data = [ { proportion: 30, format: { color: "#000000", label: 'JavaScript' }, collapsed: true, // collapse the proportion when dragged to zero }, { proportion: 40, format: { color: "#333333", label: 'HTML' }, collapsed: false, }, { proportion: 30, format: { color: "#666666", label: 'CSS' }, }, ]
var myPieChart = new DraggablePiechart({ canvas: document.getElementById('piechart'), data: data, });
4.可用于自定义饼图的选项。
var myPieChart = new DraggablePiechart({ radius: 0.9, collapsing: false, minAngle: 0.1, drawSegment: function (context, piechart, centerX, centerY, radius, startingAngle, arcSize, format, collapsed) { if (collapsed) { return; } // Draw coloured segment context.save(); var endingAngle = startingAngle + arcSize; context.beginPath(); context.moveTo(centerX, centerY); context.arc(centerX, centerY, radius, startingAngle, endingAngle, false); context.closePath(); context.fillStyle = format.color; context.fill(); context.restore(); // Draw label on top context.save(); context.translate(centerX, centerY); context.rotate(startingAngle); var fontSize = Math.floor(context.canvas.height / 25); var dx = radius - fontSize; var dy = centerY / 10; context.textAlign = "right"; context.font = fontSize + "pt Helvetica"; context.fillText(format.label, dx, dy); context.restore(); }, drawNode: function (context, piechart, x, y, centerX, centerY, hover) { context.save(); context.translate(centerX, centerY); context.fillStyle = '#DDDDDD'; var rad = hover ? 7 : 5; context.beginPath(); context.arc(x, y, rad, 0, TAU, true); context.fill(); context.stroke(); context.restore(); } });
5.每次饼图发生变化时都调用一个函数。
var myPieChart = new DraggablePiechart({ onchange: function onPieChartChange(piechart) { // get the percentage for the first slice var firstPercentage = piechart.getSliceSizePercentage(0); // get all percentages var percentages = piechart.getAllSliceSizePercentages(); } });