react d3 修改地图tootip的位置
json: https://github.com/120821/react_learn_for_d3_svg_path_20230912/blob/main/src/china_map_new.json
代码:
import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';
//import chinaData from './china.json';
import chinaData from './china_map_new.json';
const ChinaMapForTooltip = () => {
const mapRef = useRef();
nbsp; useEffect(() => {
const svg = d3.select(mapRef.current);
nbsp; // 创建投影函数
const projection = d3.geoMercator()
//.center([15, 18])
.scale(200)
//.fitSize([800, 800], chinaData);
nbsp; // 创建路径生成器
const path = d3.geoPath()
.projection(projection);
nbsp; // 绘制地图路径
svg.selectAll('path')
.data(chinaData.features)
.enter()
.append('path')
.attr('d', path)
.attr('fill', 'none')
.attr('stroke', 'white')
.attr('stroke-width', 0.8)
.on('mouseover', handleMouseOver)
.on('mouseout', handleMouseOut);
nbsp; // 处理鼠标悬停事件
function handleMouseOver(event, d) {
d3.select(this)
.attr('fill', 'none');
nbsp; // 在工具提示中显示省份名称
// 这里使用了示例的工具提示样式,你可以根据需要自定义样式
svg.append('text')
.attr('id', 'tooltip')
.attr('x', event.pageX - 80) // 修改tooltip的位置,左右
.attr('y', event.pageY - 180) // 修改tooltip的位置,上下
.text(d.properties.name)
.style('fill', 'white'); // 设置字体颜色为白色
}
nbsp; // 处理鼠标离开事件
function handleMouseOut() {
d3.select(this)
.attr('fill', 'none');
nbsp; // 移除工具提示
svg.select('#tooltip').remove();
}
}, []);
nbsp; return (
<svg ref={mapRef} width={1500} height={1000} />
);
};
export default ChinaMapForTooltip;