echarts 实现tooltip自动轮播显示,鼠标悬浮时暂停

在ECharts中,可以通过设置 tooltip.trigger="axis" ,来显示数据轴上的提示框。
实现tooltip的自动轮播显示,结合使用 setInterval()dispatchAction()方法。
获取chart DOM 实例,监听鼠标事件,悬浮时清空定时器,鼠标离开开启定时器,继续轮播。

“vue”: “^3.2.47”,
“echarts”: “^5.4.1”,

  • 效果
    在这里插入图片描述

实现步骤

  • 设置 tooltip
tooltip: {
	trigger: 'axis',
},
  • 获取当前图表数据项length,并定义 currentIndex 用于记录当前显示的数据项索引。
const xData = Array.from({ length: 31 }, (_, i) => i + 1);
let currentIndex = -1; // 初始值为-1,表示未开始轮播
  • 使用 setInterval()定时触发 dispatchAction(),切换tooltip的显示内容。
let timer = <TimerType>undefined;
let currentIndex = -1;

// 切换tooltip
function switchTooltip(myChart) {
	// 取消之前高亮的图形
	myChart.dispatchAction({
		type: 'downplay',
		seriesIndex: 1,
		dataIndex: currentIndex,
	});

	currentIndex = (currentIndex + 1) % 31;
	// 高亮当前图形
	myChart.dispatchAction({
		type: 'highlight',
		seriesIndex: 1,
		dataIndex: currentIndex,
	});
	// 显示tooltip
	myChart.dispatchAction({
		type: 'showTip',
		seriesIndex: 1,
		dataIndex: currentIndex,
	});
}

function startTooltipLoop(myChart) {
	timer = setInterval(() => switchTooltip(myChart), 3000);
}

function closeSwitchTooltip() {
	timer = undefined;
	clearInterval(timer);
}

// 开启轮播
startTooltipLoop(myChart);

  • 监听鼠标事件,悬浮时停止轮播,离开继续轮播
const myChart = echarts.init(unref(lineChartIntanse)!);

// 鼠标悬浮,停止轮播
myChart.on('mousemove', function () {
	closeSwitchTooltip();
});

// 鼠标离开,继续轮播
myChart.on('mousedown', function () {
	startTooltipLoop(myChart);
});

  • 完整代码
  • lineChart.ts
import * as echarts from 'echarts';
import { Ref } from 'vue';
import type { SalesTrendComparison, TimerType } from '../types';
import { getSize } from '../utils';

type EChartsOption = echarts.EChartsOption;

export function useLineChart(lineChartIntanse: Ref<Nullable<HTMLElement>>, data: SalesTrendComparison[]) {
	let timer = <TimerType>undefined;
	let currentIndex = -1;

	watch(
		() => data,
		async (data: Recordable) => {
			closeSwitchTooltip();
			await nextTick();
			const getLineChartInstance = unref(lineChartIntanse) ? echarts.getInstanceByDom(unref(lineChartIntanse)!) : null;
			getLineChartInstance ? getLineChartInstance.setOption({ series: getSeries(data) }) : initLineChart();
		},
		{ deep: true, immediate: true }
	);

	function initLineChart() {
		const myChart = echarts.init(unref(lineChartIntanse)!);

		const option = getOption();

		startTooltipLoop(myChart);

		myChart.on('mousemove', function () {
			closeSwitchTooltip();
		});

		myChart.on('mousedown', function () {
			startTooltipLoop(myChart);
		});

		myChart.setOption(option);
	}

	function getOption() {
		const color = '#748497';
		const xData = Array.from({ length: 31 }, (_, i) => i + 1);
		const option: EChartsOption = {
			tooltip: {
				trigger: 'axis',
				backgroundColor: '#364057',
				borderColor: 'rgba(255,255,255,0.2)',
				textStyle: {
					color: '#FFFFFF',
					lineHeight: getSize(12),
					fontSize: getSize(14),
					fontFamily: 'PingFangSC-Regular, PingFang SC',
				},
				axisPointer: {
					type: 'line',
				},
				formatter: (params) => {
					let result = '';
					params.forEach((item, i) => {
						const { seriesName, data, axisValue } = item;
						const color = seriesName === '上月' ? '#FB497C' : '#5BE4F7';
						if (i === 0) {
							result += `${axisValue}日销售额<br/>`;
						}
						result += markDot(color) + `${seriesName} ${data?.[1]}<br/>`;
					});
					return result;
				},
			},
			legend: {
				textStyle: {
					color: '#fff',
					fontSize: getSize(14),
					fontWeight: 500,
					lineHeight: getSize(12),
					fontFamily: 'PingFangSC-Medium, PingFang SC',
				},
				itemHeight: getSize(8),
			},
			grid: {
				top: '10%',
				left: '0',
				right: '4%',
				bottom: '7%',
				containLabel: true,
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: xData,
				axisLabel: {
					interval: 0,
					margin: getSize(13),
					color,
					fontSize: getSize(14),
					lineHeight: getSize(18),
					fontWeight: 600,
					fontFamily: 'PingFangSC-Regular, PingFang SC',
				},
				axisTick: { show: false },
				axisLine: {
					lineStyle: { color: '#0C3760', type: 'dashed', width: getSize(1) },
				},
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: { color: '#0C3760', type: 'dashed', width: getSize(1) },
				},
				axisLabel: {
					color,
					fontFamily: 'PingFangSC-Medium, PingFang SC',
					fontWeight: 500,
					fontSize: getSize(14),
					lineHeight: getSize(20),
					margin: getSize(12),
				},
			},

			series: getSeries(data),
		};

		return option;
	}

	// 生成大小一样样色不同的圆点
	function markDot(color) {
		let domHtml =
			'<span style="' +
			'display: inline-block;' +
			'margin-right: 8px;' +
			'margin-bottom: 2px;' +
			'border-radius: 6px;' +
			'width: 0.4167vw;' +
			'height: 0.7407vh;' +
			`background-color: ${color}` +
			'"></span>';
		return domHtml;
	}

	function getSeries(data): EChartsOption['series'] {
		const common = {
			type: 'line',
			stack: 'Total',
			animation: false,
			symbol: 'circle',
			symbolSize: getSize(8),
		};
		return data.map((item) => {
			return {
				name: item.name,
				data: item.data,
				...common,
				emphasis: {
					itemStyle: {
						color: item.color,
						borderWidth: 0,
					},
				},
				itemStyle: {
					color: '#03122F',
					borderWidth: getSize(2),
					borderColor: item.color,
				},
				lineStyle: {
					color: item.color,
					width: getSize(2),
				},
				z: item.name === '本月' ? 6 : 1,
			};
		}) as EChartsOption['series'];
	}

	// 切换tooltip
	function switchTooltip(myChart) {
		// 取消之前高亮的图形
		myChart.dispatchAction({
			type: 'downplay',
			seriesIndex: 1,
			dataIndex: currentIndex,
		});

		currentIndex = (currentIndex + 1) % 31;
		// 高亮当前图形
		myChart.dispatchAction({
			type: 'highlight',
			seriesIndex: 1,
			dataIndex: currentIndex,
		});
		// 显示tooltip
		myChart.dispatchAction({
			type: 'showTip',
			seriesIndex: 1,
			dataIndex: currentIndex,
		});
	}

	function startTooltipLoop(myChart, delay = 3000) {
		timer = setInterval(() => switchTooltip(myChart), delay);
	}

	function closeSwitchTooltip() {
		timer = undefined;
		clearInterval(timer);
	}
	
	const getSize = (size: number) => (document.body.clientWidth / 1920) * size;

	// 自适应
	const onLineChartResize = () => {
		if (unref(lineChartIntanse)) {
			const chartInstance = echarts.getInstanceByDom(unref(lineChartIntanse)!);
			const option = getOption();
			chartInstance?.setOption(option);
			chartInstance?.resize();
		}
	};

	return { onLineChartResize, switchTooltip, closeSwitchTooltip };
}

  • 引用
	<div class="chart" ref="saleRef"></div>

	const saleRef = ref<Nullable<HTMLElement>>(null);
	const { onLineChartResize, closeSwitchTooltip } = useLineChart(saleRef, data);

	window.addEventListener('resize', () => resizeChart());
	
	onBeforeUnmount(() => {
		closeSwitchTooltip();
		window.removeEventListener('resize', () => resizeChart());
	});

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 ECharts WordCloud 图表中 Tooltip自动轮播功能,可以使用 ECharts 提供的 `setInterval` 和 `clearInterval` 方法结合 Tooltip 的 `showTip` 和 `hideTip` 方法实现。 具体而言,你可以在 option 中添加以下代码: ``` tooltip: { show: false, formatter: function (params) { return 'Word: ' + params.name + '<br>Value: ' + params.value; } }, series: [{ type: 'wordCloud', // 设置其他属性 ... // 鼠标移入显示 Tooltip emphasis: { focus: 'self', textStyle: { shadowBlur: 10, shadowColor: '#333' } }, // 鼠标移出隐藏 Tooltip blur: { textStyle: { opacity: 0 } }, // 自动轮播 Tooltip animationDurationUpdate: 2000, animationEasingUpdate: 'linear', animationDelayUpdate: function (idx) { return idx * 50; }, onmouseover: function (params) { var index = params.dataIndex; var intervalId = setInterval(function () { chart.dispatchAction({ type: 'hideTip', dataIndex: index }); index = (index + 1) % data.length; chart.dispatchAction({ type: 'showTip', dataIndex: index }); }, 3000); chart.__intervalId = intervalId; }, onmouseout: function (params) { clearInterval(chart.__intervalId); } }] ``` 在这个例子中,我们首先将 Tooltip 的 `show` 属性设置为 `false`,表示一开始不显示 Tooltip。然后,我们在 WordCloud 的 `emphasis` 和 `blur` 属性中分别设置了鼠标移入和移出 Tooltip显示和隐藏样式。 接着,我们在 WordCloud 的 `onmouseover` 和 `onmouseout` 事件中分别实现鼠标移入和移出自动轮播功能。在 `onmouseover` 事件中,我们使用 `setInterval` 方法定切换 Tooltip显示内容。在 `onmouseout` 事件中,我们使用 `clearInterval` 方法清除定器。 最后,我们设置了 WordCloud 的 `animationDurationUpdate`、`animationEasingUpdate` 和 `animationDelayUpdate` 属性,用于控制 Tooltip 切换的动画效果和间隔间。 请注意,在实现自动轮播功能,需要将 ECharts 实例保存为一个变量,以便在 `onmouseout` 事件中清除定器。在本例中,我们将 ECharts 实例保存为了 `chart` 变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值