Chart.js实现柱状图鼠标悬停缩放效果的方法
实现Chart.js柱状条鼠标悬停缩放效果
要实现类似CSS transform: scale的悬停缩放效果,你可以通过Chart.js的自定义插件监听鼠标事件,在柱子hover时调整Canvas绘制上下文的缩放变换,从而实现目标效果。以下是完整的修改方案:
完整代码示例
JavaScript 部分
const thirdlabels = [ 'January', 'February', 'March', 'April', 'May', 'June', ]; const thirddata = { labels: thirdlabels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [30, 10, 20, 2, 20, 35], }] }; // 自定义柱状条缩放插件 const barZoomPlugin = { id: 'barZoom', init(chart) { // 存储当前hover的柱子索引 chart._hoveredBarIndex = null; // 监听鼠标移动事件,定位hover的柱子 chart.canvas.addEventListener('mousemove', (e) => { const elements = chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true); if (elements.length > 0) { const index = elements[0].index; if (chart._hoveredBarIndex !== index) { chart._hoveredBarIndex = index; chart.update(); // 触发重绘应用缩放 } } else { if (chart._hoveredBarIndex !== null) { chart._hoveredBarIndex = null; chart.update(); } } }); // 鼠标离开画布时重置状态 chart.canvas.addEventListener('mouseleave', () => { if (chart._hoveredBarIndex !== null) { chart._hoveredBarIndex = null; chart.update(); } }); }, beforeDraw(chart) { if (chart._hoveredBarIndex === null) return; const ctx = chart.ctx; const targetBar = chart.getDatasetMeta(0).data[chart._hoveredBarIndex]; const { x, y, width, height } = targetBar; // 保存当前画布状态,避免影响其他绘制 ctx.save(); // 以柱子中心为原点进行缩放 const centerX = x; const centerY = y + height / 2; const scaleRatio = 1.2; // 缩放比例,1.2表示放大20% ctx.translate(centerX, centerY); ctx.scale(scaleRatio, scaleRatio); ctx.translate(-centerX, -centerY); }, afterDraw(chart) { // 恢复画布初始状态 if (chart._hoveredBarIndex !== null) { chart.ctx.restore(); } } }; const thirdconfig = { type: 'bar', data: thirddata, options: { responsive: true, maintainAspectRatio: false, plugins: { tooltip: { enabled: true } // 保留默认提示框功能 } }, plugins: [barZoomPlugin] // 注册自定义插件 }; const thirdChart = new Chart( document.getElementById('myChart3'), thirdconfig );
CSS 部分
#thirdChart { width: 50%; height: 400px; /* 设置固定高度保证图表显示正常 */ margin: auto; }
HTML 部分
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Graphics</title> <link rel="stylesheet" href="style.css"> </head> <body> <div id="thirdChart"> <canvas id="myChart3" aria-label="chart" role="img"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="index.js"></script> </body> </html>
关键细节说明
- 插件工作流程:通过
init方法监听鼠标事件获取hover柱子的索引,在beforeDraw阶段修改Canvas上下文的缩放变换,对目标柱子进行放大,afterDraw阶段恢复上下文状态避免影响其他元素。 - 缩放比例调整:修改
scaleRatio的值即可调整缩放程度,1.0为原始大小,大于1为放大,小于1为缩小。 - 响应式适配:开启
responsive: true并设置容器固定高度,保证图表在不同尺寸下正常显示。
内容的提问来源于stack exchange,提问作者Philippine
相关产品推荐
相关产品推荐

