在echarts的餅圖應用時,遇到過一個需求就是鼠標移到半環上可以切換環中的文字,同時支持legend點擊事件。誤區是,鼠標移動到環上重新渲染option,以切換內部的文字。重新渲染option的做法,不能保存你原有的legend狀態。
找到一個辦法就是,只渲染環內部文字的label。
主要代碼如下:
option = { series : [ { ... type:'pie', ... label: { show: true, position: 'outside', formatter:function(params){ let nm = params.name,per = Number(params.percent).toFixed(2) ; return [`{a|${nm}}\n`,`{b|${per}%}`] }, rich: { a: { color:'#fff', fontSize:14, lineHeight: 20 }, b: { color:'yellow', fontSize:14, foneWeight:'bold' }, } }, ... }]
myChart.on('mouseover', (params) => { currName = params.name; let op = myChart.getOption(); if(params.seriesIndex === 0){ let _label = { normal:{ show: true, position: 'center', formatter: [ `{a|${params.name}}`, `{b|${params.percent + "%"}}` ].join('\n'), rich: { a: { color:'#fff', fontSize: 18, lineHeight: 30 }, b: { color:'yellow', fontSize: 20, foneWeight:'bold', textShadowBlur: 20, textShadowColor: 'yellow' }, } } } op.series[2].label = _label; myChart.setOption(op,true) } })
提供一個自己寫的demo鏈接:https://gallery.echartsjs.com/editor.html?c=xdysA_7PCd,如果對你有幫助,點個贊給點鼓勵吧~