效果圖:
用到的插件(安裝時版本號必須對應否則無效):
-
“echarts”: “^4.9.0”,
-
“echarts-gl”: “^1.1.2”,文章來源:http://www.zghlxwxcb.cn/news/detail-768190.html
代碼分兩個文件:
1.mixins.js文件:
/**
* 繪制3d圖
* @param pieData 總數(shù)據(jù)
* @param internalDiameterRatio:透明的空心占比
* @param distance 視角到主體的距離
* @param alpha 旋轉角度
* @param pieHeight 立體的高度
* @param opacity 餅或者環(huán)的透明度
* @param dropSize 餅圖下的點的大小
*/
const getPie3D = (
pieData,
internalDiameterRatio,
distance,
alpha,
pieHeight,
opacity = 1,
dropSize,
) => {
const series = [];
let sumValue = 0;
let startValue = 0;
let endValue = 0;
let legendData = [];
let legendBfb = [];
const k = 1 - internalDiameterRatio;
pieData.sort((a, b) => {
return b.value - a.value;
});
// 為每一個餅圖數(shù)據(jù),生成一個 series-surface 配置
for (let i = 0; i < pieData.length; i++) {
sumValue += pieData[i].value;
const seriesItem = {
name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
type: 'surface',
parametric: true,
wireframe: {
show: false,
},
pieData: pieData[i],
pieStatus: {
selected: false,
hovered: false,
k,
},
center: ['10%', '50%'],
};
if (typeof pieData[i].itemStyle !== 'undefined') {
const itemStyle = {};
itemStyle.color =
typeof pieData[i].itemStyle.color !== 'undefined' ? pieData[i].itemStyle.color : opacity;
itemStyle.opacity =
typeof pieData[i].itemStyle.opacity !== 'undefined'
? pieData[i].itemStyle.opacity
: opacity;
seriesItem.itemStyle = itemStyle;
}
series.push(seriesItem);
}
// 使用上一次遍歷時,計算出的數(shù)據(jù)和 sumValue,調用 getParametricEquation 函數(shù),
// 向每個 series-surface 傳入不同的參數(shù)方程 series-surface.parametricEquation,也就是實現(xiàn)每一個扇形。
legendData = [];
legendBfb = [];
for (let i = 0; i < series.length; i++) {
endValue = startValue + series[i].pieData.value;
series[i].pieData.startRatio = startValue / sumValue;
series[i].pieData.endRatio = endValue / sumValue;
const arr =
series.length &&
series.map((item) => {
return item.pieData.value;
});
const temp = [];
arr.forEach((item) => {
if (!temp.includes(item)) {
temp.push(item);
}
});
const h = temp.length === 1 ? 5 : series[i].pieData.value;
series[i].parametricEquation = getParametricEquation(
series[i].pieData.startRatio,
series[i].pieData.endRatio,
false,
false,
k,
h,
);
startValue = endValue;
const bfb = fomatFloat(series[i].pieData.value / sumValue, 4);
legendData.push({
name: series[i].name,
value: bfb,
});
legendBfb.push({
name: series[i].name,
value: bfb,
});
}
const boxHeight = getHeight3D(series, pieHeight); // 通過pieHeight設定3d餅/環(huán)的高度,單位是px
// 準備待返回的配置項,把準備好的 legendData、series 傳入。
const option = {
legend: {
selectedMode: false,
show: Object.freeze(false),
data: legendData,
orient: Object.freeze('horizontal'),
left: Object.freeze('center'),
top: Object.freeze('bottom'),
// 圖例文字每項之間的間隔
itemGap: Object.freeze(15),
textStyle: {
color: '#fff',
fontSize: dropSize,
},
icon: Object.freeze('circle'),
formatter(param) {
const item = legendBfb.filter((val) => val.name === param)[0];
return `${item.name} `;
},
},
labelLine: Object.freeze({
show: false,
lineStyle: {
color: '#fff',
},
}),
label: Object.freeze({
show: false,
position: 'outside',
formatter: ' \n{c} n5n3t3z%',
}),
tooltip: {
// backgroundColor: Object.freeze('#033b77'),
// borderColor: Object.freeze('#21f2c4'),
textStyle: Object.freeze({
color: '#fff',
fontSize: 13,
}),
formatter: (params) => {
if (params.seriesName !== 'mouseoutSeries') {
const endRatioTemp =
option.series[params.seriesIndex].pieData &&
option.series[params.seriesIndex].pieData.endRatio;
const startRatioTemp =
option.series[params.seriesIndex].pieData &&
option.series[params.seriesIndex].pieData.startRatio;
const bfb = ((endRatioTemp - startRatioTemp) * 100).toFixed(2);
// 最初始的
// return (
// !isNaN(bfb) ? (`${params.seriesName}<br/>` +
// `<span style='display:inline-block;margin-right:.3125rem;border-radius:.625rem;width:.625rem;height:.625rem;background-color:${params.color};'></span>` +
// `${bfb}%`) : ''
// );
return !isNaN(bfb)
? `<span style='font-size:${dropSize}px;'>${params.seriesName}</span><br/>` +
`<span style='display:inline-block;margin-right:.3125rem;border-radius:.625rem;width:.625rem;height:.625rem;background-color:${params.color};'></span>` +
`${bfb}%`
: '';
}
},
},
xAxis3D: {
min: -1,
max: 1,
},
yAxis3D: {
min: -1,
max: 1,
},
zAxis3D: {
min: -1,
max: 1,
},
grid3D: {
show: false,
boxHeight, // 圓環(huán)的高度
viewControl: {
// 3d效果可以放大、旋轉等,請自己去查看官方配置
alpha: 35, // 角度
distance, // 調整視角到主體的距離,類似調整zoom
rotateSensitivity: 0, // 設置為0無法旋轉
zoomSensitivity: 0, // 設置為0無法縮放
panSensitivity: 0, // 設置為0無法平移
autoRotate: false, // 自動旋轉
},
},
series,
};
return option;
};
/**
* 生成扇形的曲面參數(shù)方程,用于 series-surface.parametricEquation
*/
const getParametricEquation = (startRatio, endRatio, isSelected, isHovered, k, h) => {
// 計算
const midRatio = (startRatio + endRatio) / 2;
const startRadian = startRatio * Math.PI * 2;
const endRadian = endRatio * Math.PI * 2;
const midRadian = midRatio * Math.PI * 2;
// 如果只有一個扇形,則不實現(xiàn)選中效果。
if (startRatio === 0 && endRatio === 1) {
isSelected = false;
}
// 通過扇形內徑/外徑的值,換算出輔助參數(shù) k(默認值 1/3)
k = typeof k !== 'undefined' ? k : 1 / 3;
// 計算選中效果分別在 x 軸、y 軸方向上的位移(未選中,則位移均為 0)
const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
// 計算高亮效果的放大比例(未高亮,則比例為 1)
const hoverRate = isHovered ? 1.05 : 1;
// 返回曲面參數(shù)方程
return {
u: {
min: -Math.PI,
max: Math.PI * 3,
step: Math.PI / 32,
},
v: {
min: 0,
max: Math.PI * 2,
step: Math.PI / 20,
},
x(u, v) {
if (u < startRadian) {
return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
}
if (u > endRadian) {
return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
}
return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
},
y(u, v) {
if (u < startRadian) {
return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
}
if (u > endRadian) {
return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
}
return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
},
z(u, v) {
if (u < -Math.PI * 0.5) {
return Math.sin(u);
}
if (u > Math.PI * 2.5) {
// console.log('if內部h', h);
// console.log('if內部結果', Math.sin(u) * h * 0.1);
return Math.sin(u) * h * 0.2;
// return Math.sin(u) * 13 * 0.1;
}
// console.log('if外部h', h);
// console.log('if外部結果', Math.sin(v) > 0 ? 1 * h * 0.1 : -1);
return Math.sin(v) > 0 ? 1 * h * 0.2 : -1;
// return Math.sin(v) > 0 ? 1 * 13 * 0.1 : -1;
},
};
};
/**
* 獲取3d丙圖的最高扇區(qū)的高度
*/
const getHeight3D = (series, height) => {
const arr =
series.length &&
series.map((item) => {
return item.pieData.value;
});
const temp = [];
arr.forEach((item) => {
if (!temp.includes(item)) {
temp.push(item);
}
});
series.sort((a, b) => {
return b.pieData.value - a.pieData.value;
});
const result = temp.length === 1 ? 25 : (height * 25) / series[0].pieData.value;
return result;
};
/**
* 格式化浮點數(shù)
*/
const fomatFloat = (num, n) => {
let f = parseFloat(num);
if (isNaN(f)) {
return false;
}
f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 冪
let s = f.toString();
let rs = s.indexOf('.');
// 判定如果是整數(shù),增加小數(shù)點再補0
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + n) {
s += '0';
}
return s;
};
export { getPie3D, getParametricEquation };
2.pieChart.vue文件:
<template>
<div class="chart-container">
<div class="chart" ref="chart"></div>
</div>
</template>
<script>
import echarts from 'echarts';
// import _ from 'lodash';
import 'echarts-gl';
import { getPie3D, getParametricEquation } from './mixins/index';
const color = ['#2C6DEF', '#AC2424', '#2DB62E', '#DCC436', '#804AE8', '#25C5DA'];
export default {
name: 'chart',
props: {
netDefenseSituList: {
type: Array,
default: () => [],
},
},
data() {
return {
optionData: [],
statusChart: null,
option: {},
};
},
created() {
this.setLabel();
},
mounted() {
this.initChart();
window.addEventListener('resize', this.resizeChart);
},
watch: {
netDefenseSituList: {
deep: true,
immediate: true,
handler(val) {
const tempArr = [];
val.forEach((item) => {
tempArr.push({
name: item.title,
value: item.defenseNumber,
});
});
this.optionData = tempArr;
},
},
},
methods: {
resizeChart() {
this.changeSize();
},
setLabel() {
const fontFamily = 'sans-serif';
const fontSize = this.chartFontSize;
const textStyle = {
fontSize,
fontFamily,
};
const { pieLength, pieLineHeight } = this.adapterData;
this.optionData.forEach((item, index) => {
item.legend = {
show: false,
};
item.itemStyle = {
color: color[index],
};
item.textStyle = { ...textStyle };
item.label = {
normal: {
show: false,
// color: color[index],
color: '#ffffff',
fontSize,
fontFamily,
position: Object.freeze('right'),
offset: [0, 3],
textStyle: {
...textStyle,
color: '#ffffff',
},
formatter: ['{b|}', '{d|n5n3t3z%}'].join('\n'), // 用\n來換行
rich: {
b: {
color: '#ffffff',
fontSize,
fontFamily,
lineHeight: 25,
align: Object.freeze('left'),
},
c: {
color: '#ffffff',
fontSize,
fontFamily,
textShadowColor: Object.freeze('#1c90a6'),
textShadowOffsetX: 0,
textShadowOffsetY: 2,
textShadowBlur: 5,
},
d: {
color: '#ffffff',
fontSize,
fontFamily,
lineHeight: pieLineHeight,
align: Object.freeze('left'),
},
},
},
};
item.labelLine = {
normal: {
show: false,
length: 0,
length2: Object.freeze(0),
// smooth: true,
lineStyle: {
width: 0,
// color: color[index],
color: '#ffffff',
},
},
};
});
},
initChart() {
const fontFamily = 'sans-serif';
const fontSize = this.chartFontSize - 4;
this.statusChart = echarts.init(this.$refs.chart);
// this.option = getPie3D(this.optionData, 0.75, 180, 30, 6, 1, this.chartFontSizeTwo);
this.option = getPie3D(this.optionData, 0.75, this.pieView, 30, 6, 1, this.chartFontSizeTwo);
this.statusChart.setOption(this.option);
// 是否需要label指引線,如果要就添加一個透明的2d餅狀圖并調整角度使得labelLine和3d的餅狀圖對齊,并再次setOption
this.option.series.push({
backgroundColor: Object.freeze('transparent'),
type: Object.freeze('pie'),
label: Object.freeze({
opacity: 0,
color: '#ffffff',
fontSize,
fontFamily,
lineHeight: 0,
}),
// startAngle: -40, // 起始角度,支持范圍[0, 360]。
startAngle: -30, // 起始角度,支持范圍[0, 360]。
clockwise: false, // 餅圖的扇區(qū)是否是順時針排布。上述這兩項配置主要是為了對齊3d的樣式
// radius: Object.freeze(['20%', '60%']),
// center: Object.freeze(['50%', '50%']),
radius: Object.freeze(['20%', '45%']),
center: Object.freeze(['50%', '50%']),
data: this.optionData,
itemStyle: Object.freeze({
opacity: 0, // 這里必須是0,不然2d的圖會覆蓋在表面
}),
// pieStatus: {
// // selected: false,
// // hovered: false,
// // k: 0,
// },
// pieData: {
// // startRatio: 0,
// },
});
this.option = {
...this.option,
tooltip: {
textStyle: {
color: '#ffffff',
fontSize,
fontFamily,
},
},
grid: {
top: '2%',
left: '8%',
},
};
this.statusChart.setOption(this.option);
this.bindListen(this.statusChart);
},
// 監(jiān)聽鼠標事件,實現(xiàn)餅圖選中效果(單選),近似實現(xiàn)高亮(放大)效果。
// optionName是防止有多個圖表進行定向option傳遞,單個圖表可以不傳,默認是opiton
bindListen(myChart, optionName = 'option') {
// let selectedIndex = '';
let hoveredIndex = '';
// 監(jiān)聽 mouseover,近似實現(xiàn)高亮(放大)效果
// myChart.on('mouseover', (params) => {
// // 準備重新渲染扇形所需的參數(shù)
// let isSelected;
// let isHovered;
// let startRatio;
// let endRatio;
// let k;
// // 如果觸發(fā) mouseover 的扇形當前已高亮,則不做操作
// if (hoveredIndex === params.seriesIndex) {
// // 否則進行高亮及必要的取消高亮操作
// } else {
// // 如果當前有高亮的扇形,取消其高亮狀態(tài)(對 option 更新)
// if (hoveredIndex !== '') {
// // 從 option.series 中讀取重新渲染扇形所需的參數(shù),將是否高亮設置為 false。
// isSelected = this[optionName].series[hoveredIndex].pieStatus.selected;
// isHovered = false;
// startRatio = this[optionName].series[hoveredIndex].pieData.startRatio;
// endRatio = this[optionName].series[hoveredIndex].pieData.endRatio;
// k = this[optionName].series[hoveredIndex].pieStatus.k;
// // 對當前點擊的扇形,執(zhí)行取消高亮操作(對 option 更新)
// this[optionName].series[hoveredIndex].parametricEquation = getParametricEquation(
// startRatio,
// endRatio,
// isSelected,
// isHovered,
// k,
// this[optionName].series[hoveredIndex].pieData.value,
// );
// this[optionName].series[hoveredIndex].pieStatus.hovered = isHovered;
// // 將此前記錄的上次選中的扇形對應的系列號 seriesIndex 清空
// hoveredIndex = '';
// }
// // 如果觸發(fā) mouseover 的扇形不是透明圓環(huán),將其高亮(對 option 更新)
// if (params.seriesName !== 'mouseoutSeries') {
// isSelected =
// this[optionName].series[params.seriesIndex].pieStatus &&
// this[optionName].series[params.seriesIndex].pieStatus.selected;
// isHovered = true;
// startRatio =
// this[optionName].series[params.seriesIndex].pieData &&
// this[optionName].series[params.seriesIndex].pieData.startRatio;
// endRatio =
// this[optionName].series[params.seriesIndex].pieData &&
// this[optionName].series[params.seriesIndex].pieData.endRatio;
// k =
// this[optionName].series[params.seriesIndex].pieStatus &&
// this[optionName].series[params.seriesIndex].pieStatus.k;
// // -------
// // 對當前點擊的扇形,執(zhí)行高亮操作(對 option 更新)
// this[optionName].series[params.seriesIndex].parametricEquation = getParametricEquation(
// startRatio,
// endRatio,
// isSelected,
// isHovered,
// k,
// _.get(this[optionName], 'series[params.seriesIndex].pieData.value', 0) + 10,
// );
// this[optionName].series[params.seriesIndex].pieStatus.hovered = isHovered;
// // 記錄上次高亮的扇形對應的系列號 seriesIndex
// hoveredIndex = params.seriesIndex;
// }
// // 使用更新后的 option,渲染圖表
// myChart.setOption(this[optionName]);
// }
// });
// 修正取消高亮失敗的 bug
myChart.on('globalout', () => {
// 準備重新渲染扇形所需的參數(shù)
let isSelected;
let isHovered;
let startRatio;
let endRatio;
let k;
if (hoveredIndex !== '') {
// 從 option.series 中讀取重新渲染扇形所需的參數(shù),將是否高亮設置為 true。
isSelected = this[optionName].series[hoveredIndex].pieStatus.selected;
isHovered = false;
k = this[optionName].series[hoveredIndex].pieStatus.k;
startRatio = this[optionName].series[hoveredIndex].pieData.startRatio;
endRatio = this[optionName].series[hoveredIndex].pieData.endRatio;
// 對當前點擊的扇形,執(zhí)行取消高亮操作(對 option 更新)
this[optionName].series[hoveredIndex].parametricEquation = getParametricEquation(
startRatio,
endRatio,
isSelected,
isHovered,
k,
this[optionName].series[hoveredIndex].pieData.value,
);
this[optionName].series[hoveredIndex].pieStatus.hovered = isHovered;
// 將此前記錄的上次選中的扇形對應的系列號 seriesIndex 清空
hoveredIndex = '';
}
// 使用更新后的 option,渲染圖表
myChart.setOption(this[optionName]);
});
},
// 自適應寬高
changeSize() {
this.statusChart.resize();
},
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeChart);
},
};
</script>
<style lang="less" scoped>
.chart-container {
// position: relative;
/* width: 549px; */
/* height: 472px; */
width: 100%;
height: 100%;
padding-bottom: 20px;
flex: 1;
.chart {
z-index: 1;
}
.chart {
width: 100%;
height: 100%;
}
}
</style>
頁面引用:
netDefenseSituList:為傳入的數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-768190.html
<pic-chart :netDefenseSituList="netDefenseSituList" />
到了這里,關于echarts寫3d圓環(huán),并解決圓環(huán)數(shù)據(jù)相同時顯示異常問題的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!