echarts環形圖點擊旋轉並高亮


通過計算某個扇形區域的值占整個圓的百分比來得到這個扇形的角度,從而根據startAngle這個屬性來設定圖形的開始渲染的角度,使點擊某個扇形時圓環旋轉使之始終對准某個點。
期間考慮到某扇形區域太小點擊不到,來設置最小扇形區域。
const myChartContainer = document.getElementById( 'chart' );
const myChart = echarts.init( myChartContainer );
let minAngle = 30;// 最小扇形區域為30
for ( let i = 0; i < obj.data.length; i++ ) { //某項數據為0時,最小扇形區域為0
 if ( obj.data[ i ].value === 0 ) {
  minAngle = 0;
  break;
 }
}
const pieValue = obj.data.map( v => { 
 return v.value;
} )
const sum = pieValue.reduce( ( prev, cur ) => {//數據值的總和
 return prev + cur;
}, 0 );

const sum2 = pieValue.reduce( ( prev, cur ) => {
 if ( cur < sum / 12 && cur > 0 ) {//某個值大於0小於總和的1/12即30時,按30計算和
  return prev + sum / 12;
 }
 return prev + cur;
}, 0 );
let initPieValue = pieValue[ 0 ];// 初始值
if ( initPieValue < sum / 12 && initPieValue > 0 ) {
 initPieValue = sum / 12;
}
const option = {
tooltip: {
 show: false,
 trigger: 'item',
 formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
 show: false,
 orient: 'vertical',
 x: 'left'
},
color: [ '#44bbf8', '#93e588', '#ffd87b', '#f88071' ],
series: [
{
 name: '',
 type: 'pie',
 radius: [ '45%', '79%' ],
 clockWise: false,
 startAngle: 167 - ( initPieValue / sum2 * 360 / 2 ),
 minAngle: minAngle,
 avoidLabelOverlap: false,
itemStyle: {
 emphasis: {
  radius: [ '46%', '100%' ]
 }
},
label: {
 normal: {
  show: false,
  position: 'center'
 },
 emphasis: {
  show: false,
  textStyle: {
  fontSize: '30',
  fontWeight: 'bold'
  }
 }
},
labelLine: {
  normal: {
   show: false
  }
},
 data: obj.data
  }
 ]
};
myChart.setOption( option );
if ( minAngle === 30 ) {  //最小扇形區域30時
myChart.dispatchAction( { type: 'highlight', seriesIndex: 0, dataIndex: 0 } );
}

let preDataIndex = 0;
myChart.on( 'click', ( v ) => {
 if ( v.dataIndex === preDataIndex ) {
  myChart.dispatchAction( {
  type: 'highlight',
  seriesIndex: 0,
  dataIndex: v.dataIndex
 } );
 return;
}
const sum1 = pieValue.reduce( ( prev, cur, index ) => {
 if ( index < v.dataIndex ) {
  if ( cur < sum / 12 && cur > 0 ) {
   return prev + sum / 12; // 餅圖的扇形最小角度設置為30,占圓的1/12
  }
  return prev + cur;
 }
 return prev;
}, 0 );
let curPieValue = pieValue[ v.dataIndex ];
if ( curPieValue < sum / 12 && curPieValue > 0 ) {
 curPieValue = sum / 12;
}
option.series[ 0 ].startAngle = 167 - ( sum1 / sum2 * 360 + curPieValue / sum2 * 360 / 2 );// 開始渲染圖形的角度
myChart.setOption( option );
preDataIndex = v.dataIndex;
window.setTimeout( () => {
 myChart.dispatchAction( {
 type: 'highlight',
 seriesIndex: 0,
 dataIndex: v.dataIndex
 } );
}, 400 );

this.mrkName = v.data.name;
this.mrkValue = v.data.value;
} );


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM