echarts饼图中心呈现一张图片,并且能动态旋转的效果react组件
实现效果:
父组件:
import React from 'react'
import styles from './style.less'
import GaugeChart from './GaugeChart';export default function index() {return (<div><div className={styles.bg} ></div><div style={{ width: '500px', height: '500px' }}><GaugeChart value={65.23} title="数据" /></div></div>)
}
子组件:
import React, { useEffect, useRef } from 'react';
import * as echarts from "echarts";
import totalBg from '@assets/images/icon1@2x.png';const MyChart = () => {const chartRef = useRef(null);const intervalIdRef = useRef(null); // 使用ref保存intervalIduseEffect(() => {const myChart = echarts.init(chartRef.current);const pieOption = {series: [{type: 'pie',radius: ['40%', '70%'],center: ['50%', '50%'],data: [{ value: 335, name: '直接访问' },{ value: 310, name: '邮件营销' },{ value: 234, name: '联盟广告' },{ value: 135, name: '视频广告' },{ value: 1548, name: '搜索引擎' }],itemStyle: {emphasis: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: 'rgba(0, 0, 0, 0.5)'}}}]};myChart.setOption(pieOption);const timer = setTimeout(() => {const earthOption = {graphic: [{type: 'group',left: 'center',top: 'center',rotation: 0,rotationX: 0,rotationY: 0,children: [{type: 'image',style: {image: totalBg,width: 60,height: 60,shadowBlur: 20,shadowColor: 'rgba(0, 0, 0, 0.5)'},z: 10,zlevel: 10}]}]};myChart.setOption(earthOption);let rotationX = 0;let rotationY = 0;let rotationZ = 0;intervalIdRef.current = setInterval(() => {rotationX += 0.5;rotationY += 1;rotationZ += 0.5;// 检查图表实例是否已被销毁if (!myChart.isDisposed()) {myChart.setOption({graphic: [{type: 'group',left: 'center',top: 'center',rotation: rotationZ,rotationX: rotationX,rotationY: rotationY,children: [{type: 'image',style: {image: totalBg,width: 60,height: 60,shadowBlur: 20,shadowColor: 'rgba(0, 0, 0, 0.5)'},z: 10,zlevel: 10}]}]});}}, 100);}, 1000);return () => {// 清除定时器和超时clearTimeout(timer);if (intervalIdRef.current) {clearInterval(intervalIdRef.current);}// 销毁图表实例myChart.dispose();};}, []);return (<div ref={chartRef} style={{ width: '400px', height: '400px', perspective: '1000px' }} />);
};export default MyChart;