简体   繁体   中英

How to make space around bar clickable in echarts bar chart?

The 'click' event gets triggered only when clicked exactly inside the bar. This is not convenient if we have a bar with small width or height. When i hover the bar, some space around the bar is highlighted with full chart height and tooltip is displayed. i want to make the highlighted region clickable and the bar data should be available in the event. I have gone through the docs and tried chart.on('click', 'xAxis.category', function () {...}); But the function is not triggered.

In this demo, Alert is triggered only when i click inside a bar. How do i make the surrounding area clickable?

https://codesandbox.io/s/cocky-banzai-6j5pg?file=/src/Chart.js

It's true, you cannot receive the common event when click outside bar but Echarts is mature framework and almost any events can received with low-level object zRender . You need to get access to zRender with getZr() and then convert coordinates of the clicked pixel to chart coordinates. After it you will have index of series datapoint and with this to fetch category will be easy.

myChart.getZr().on('click', params => {
  var pointInPixel = [params.offsetX, params.offsetY];
  var pointInGrid = myChart.convertFromPixel('grid', pointInPixel);
  var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]]
  console.log(category);
});

See example:

 var myChart = echarts.init(document.getElementById('main')); var option = { title: { text: 'ECharts' }, tooltip: {}, legend: { data: ['Label'] }, xAxis: { data: ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6"] }, yAxis: {}, tooltip: { trigger: "axis", confine: true, enterable: true, axisPointer: { type: "shadow", shadowStyle: { color: "rgba(255,0,0, 0.5)" } }, backgroundColor: "rgba(255,255,255,1)", textStyle: { color: "#6D6D70" }, extraCssText: `box-shadow: 3px 6px 14px #cccccc61;border-radius: 10px;` }, series: [{ name: 'Series', type: 'bar', data: [5, 20, 36, 10, 10, 20], showBackground: true, }] }; myChart.setOption(option); myChart.getZr().on('click', params => { var pointInPixel = [params.offsetX, params.offsetY]; var pointInGrid = myChart.convertFromPixel('grid', pointInPixel); var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]] console.log(category); });
 <script src="https://cdn.jsdelivr.net/npm/echarts@4.9.0/dist/echarts.min.js"></script> <div id="main" style="width: 600px;height:400px;"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM