UNPKG

light-chart

Version:

Charts for mobile visualization.

104 lines (98 loc) 2.5 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <title>柱状图选中</title> <link rel="stylesheet" href="./assets/common.css"> <style> .chart-label { text-align: center; font-size: 12px; font-weight: normal; color: #808080; } </style> </head> <body> <div> <canvas id="mountNode"></canvas> </div> <script src="./assets/jquery-3.2.1.min.js"></script> <script src="https://gw.alipayobjects.com/os/rmsportal/NjNldKHIVQRozfbAOJUW.js"></script> <script src="../build/f2-all.js"></script> <script src="https://gw.alipayobjects.com/os/rmsportal/NjNldKHIVQRozfbAOJUW.js"></script> <script> var data = [ { year: '1951 年', sales: 38 }, { year: '1952 年', sales: 52 }, { year: '1956 年', sales: 61 }, { year: '1957 年', sales: 145 }, { year: '1958 年', sales: 48 }, { year: '1959 年', sales: 38 }, { year: '1960 年', sales: 38 }, { year: '1962 年', sales: 38 }, ]; var chart = new F2.Chart({ id: 'mountNode', pixelRatio: window.devicePixelRatio }); chart.source(data, { sales: { tickCount: 5 } }); chart.tooltip(false); chart.interval().position('year*sales'); chart.render(); // 绘制文本 const offset = -5; const canvas = chart.get('canvas'); const group = canvas.addGroup(); const Shape = F2.G.Shape; const shapes = {}; data.map(obj => { const point = chart.getPosition(obj); const text = group.addShape('text', { attrs: { x: point.x, y: point.y + offset, text: obj.sales, textAlign: 'center', textBaseline: 'bottom', fill: '#ccc' } }); shapes[obj.year] = text; // 缓存该 shape, 便于后续查找 }); let lastTextShape; // 上一个被选中的 text chart.interaction('interval-select', { selectStyle: { stroke: '#000', lineWidth: 1 }, selectAxisStyle: { fill: '#000', fontWeight: 'bold' }, mode: 'range', onEnd(ev) { const { data, selected } = ev; lastTextShape && lastTextShape.attr({ fill: '#ccc', fontWeight: 'normal' }); if (selected) { const textShape = shapes[data.year]; textShape.attr({ fill: '#000', fontWeight: 'bold' }) lastTextShape = textShape; } canvas.draw(); } }); </script> </body> </html>