D3 获得鼠标的真实位置

此处说明的是V5版本

 

//在缩放的事件中将 transform 存储为this
注:(这个变量在缩放和平移的过程中,会更新此变量)
var transform = d3.zoomTransform(ele);
this.transform = transform;

//在获得真实坐标的时候,缩放和偏移的变量进行核算
var translateVar = [0, 0];
if (this.transform) {
    translateVar[0] = this.transform.x;
    translateVar[1] = this.transform.y;
}

var scaleVar = this.transform.k;
if (!scaleVar) {
    scaleVar = 1;
}
var coordinates = d3.mouse(this);
var x = (coordinates[0] - translateVar[0]) / scaleVar;
var y = (coordinates[1] - translateVar[1]) / scaleVar;

此时x,y 为真实坐标

研究了一下午。如果帮助到了你,请点个赞~       

以下是使用d3.js获得地图位置名称的代码示例: ```javascript // 创建一个地图投影 var projection = d3.geoMercator() .scale(120) .translate([width / 2, height / 2]); // 创建一个地理路径生成器 var path = d3.geoPath() .projection(projection); // 加载地图数据 d3.json("path/to/map/data.json", function(error, map) { if (error) throw error; // 将地图绘制到SVG上 svg.selectAll("path") .data(map.features) .enter().append("path") .attr("d", path) .attr("fill", "#ccc") .attr("stroke", "#fff") .attr("stroke-width", 0.5); // 添加鼠标移动事件,显示位置名称 svg.on("mousemove", function() { var mouse = d3.mouse(this); var point = projection.invert(mouse); var location = findLocation(map, point); tooltip.style("display", "block") .style("left", (d3.event.pageX + 10) + "px") .style("top", (d3.event.pageY - 25) + "px") .text(location); }); // 添加鼠标移出事件,隐藏位置名称 svg.on("mouseout", function() { tooltip.style("display", "none"); }); // 在SVG上添加提示框元素 var tooltip = d3.select("body").append("div") .attr("class", "tooltip"); }); // 根据坐标点查找位置名称 function findLocation(map, point) { for (var i = 0; i < map.features.length; i++) { var feature = map.features[i]; if (d3.geoContains(feature, point)) { return feature.properties.name; } } return ""; } ``` 此代码将创建一个地图投影,并使用d3.geoPath()生成器将地图绘制到SVG上。然后,添加了鼠标移动和移出事件来显示和隐藏位置名称。最后,使用findLocation()函数在地图数据中查找位置名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值